首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL:如何根据不同的条件从一列中提取数据作为不同的列?

SQL:如何根据不同的条件从一列中提取数据作为不同的列?
EN

Stack Overflow用户
提问于 2014-03-12 10:42:24
回答 6查看 48关注 0票数 0

我有很多接入点,每个AP有两个射频卡,每个射频卡有一个频道号码。

代码语言:javascript
复制
AP_idx | RF_idx | Channel |
   0   |    0   |    7    |
   0   |    1   |    136  |
   1   |    0   |    11   |
   1   |    1   |    128  |
   2   |    0   |    4    |
   2   |    1   |    149  |

现在我需要AP_idx和(RF0通道,RF1通道)之间的映射,参见下面的示例

代码语言:javascript
复制
AP_idx | ChannelA | ChannelB |
   0   |    7     |    136   |
   1   |    11    |    128   |
   2   |    4     |    149   |

我想要channelA频道,RF_idx == 0频道,RF_idx == 1频道

如何设计SQL语句?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2014-03-12 10:50:35

如果我正确理解,你想要“枢轴”数据。在SQLite中,通过使用group by实现这一目的的一种方法

代码语言:javascript
复制
select AP_idx,
       max(case when RF_idx = 0 then Channel end) as ChannelA,
       max(case when RF_idx = 1 then Channel end) as ChannelB
from table t
group by AP_idx;

另一种方法是使用join

代码语言:javascript
复制
select ta.AP_idx, ta.channel as ChannelA, tb.channel as ChannelB
from table ta join
     table tb
     on ta.AP_idx = tb.AP_idx and
        ta.RF_idx = 0 and
        tb.RF_idx = 1;

使用正确的索引,这可能具有更好的性能。另一方面,如果缺少一些通道值,则聚合方法更安全。

票数 2
EN

Stack Overflow用户

发布于 2014-03-12 10:55:49

代码语言:javascript
复制
select AP_idx, ChannelA, ChannelB
from (select AP_idx, Channel AS ChannelA WHERE RF_idx = 0) AS T1
inner join
(select AP_idx, Channel AS ChannelB WHERE RF_idx = 1) AS T2
using (AP_idx)
票数 2
EN

Stack Overflow用户

发布于 2014-03-12 10:54:59

SQL:

代码语言:javascript
复制
select a.AP_idx, a.Channel, b.Channel
  from (select AP_idx, RF_idx, Channel from t where RF_idx = 0) as a,
       (select AP_idx, RF_idx, Channel from t where RF_idx = 1) as b
 where a.AP_idx = b.AP_idx;

结果:

代码语言:javascript
复制
0|7|136
1|11|128
2|4|149
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22348948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档