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

时间:2014-03-12 10:42:24

标签: sql sqlite

我有很多接入点,每个AP有两个RF卡,每个RF卡都有一个通道号。

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通道)之间的映射,请参阅以下示例

AP_idx | ChannelA | ChannelB |
   0   |    7     |    136   |
   1   |    11    |    128   |
   2   |    4     |    149   |

当RF_idx == 0时,我想将频道作为channelA,当RF_idx == 1

时,我希望频道作为channelB

如何设计SQL语句?

6 个答案:

答案 0 :(得分:2)

如果我理解正确,你想" pivot"数据。在SQLite中,使用group by

执行此操作的一种方法
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

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;

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

答案 1 :(得分:2)

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 :(得分:1)

SQL:

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;

结果:

0|7|136
1|11|128
2|4|149

答案 3 :(得分:0)

如果需要根据一个字段显示不同的字段作为频道。语法是

select AP_idx, 
    RF_idx, 
    case RF_ixd
        when 0 then ChannelA
        else ChannelB
        end as channel
from mytable

如果您需要将频道字段映射到不同的列,那么您可以尝试

select AP_idx, 
    sum(case RF_ixd
        when 0 then channel
        else 0
        end) as channelA,
    sum(case RF_ixd
        when 1 then channel
        else 0
        end) as channelB
from mytable
group by RF_idx

答案 4 :(得分:0)

我认为这就是你所追求的目标:

select T1.Ap_idx,T1.RF_idx, Case RF_idx WHEN 0 THEN T2.ChannelA ELSE T2.ChannelB END As Channel
FROM Table1 T1 LEFT OUTER JOIN
Table2 T2 on T1.AP_idx=T2.AP_idx

结果:

AP_idx  RF_idx  Channel
0        0       7
0        1       136
1        0       11
1        1       128
2        0       4
2        1       149

答案 5 :(得分:0)

假设表名是APinfo。

SELECT ap_idx, sum(RF_idx = 0 THEN Channel ELSE 0 END的情况)为'ChannelA', sum(RF_idx = 1 THEN Channel ELSE 0 END的情况)为'ChannelB' 来自ap_idx 分组由ap_idx

这些条件语句取决于您所在的数据库。