2014-03-12 77 views
0

我有很多接入點,每個AP有兩個射頻卡,每個射頻卡都有一個通道號。SQL:如何根據不同的條件從一列中提取數據作爲不同的列?

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 | 

我想信道作爲channelA,當RF_idx == 0,和信道作爲channelB當RF_idx == 1

如何設計SQL語句?

回答

2

如果我理解正確的話,你想「轉動」數據的語法是

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

。在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; 

這可能有正確的索引更好的性能。另一方面,如果某些通道值丟失,則聚合方法更安全。

0

如果您需要根據一個字段顯示不同的字段作爲通道。如果你需要映射通道字段不同的列,那麼你可以嘗試

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 
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 
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 
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) 
0

假設表名是APinfo。

SELECT ap_idx, 總和(情況下,當RF_idx = 0 THEN通道ELSE 0 END)爲 'ChannelA', 總和(情況下,當RF_idx = 1 THEN通道ELSE 0 END),如通過 'ChannelB' 從ap_idx 組ap_idx

這些條件語句取決於您所在的數據庫。

相關問題