2014-10-12 89 views
0

我有一個關於車站地鐵卡的表格輸入和記錄record(cid, enter_sid, exit_sid) 我想獲得每個車站出入的總數。 例如,如何結合查詢結果?

cid enter_sid exit_sid 1 1 2 1 1 2 1 2 3 2 2 1

我想

sid count(*) 
1   3 
2   4 
3   1 

我不知道該怎麼select cid, count(*) from record group by enter_sidselect cid, count(*) from record group by exit_sid

CID結合意味着卡的ID。 對於我預期結果的第一行,1代表站的ID,3代表sid 1在enter_sid中存在2次,在exit_sid中存在1次。

+0

究竟什麼是你的'cid'列? – 2014-10-12 03:33:29

+0

您的預期結果如何與列值和/或數值匹配? – 2014-10-12 03:42:17

+0

卡的ID,在這種情況下沒有多大意義。 – cow12331 2014-10-12 03:43:38

回答

2

對此的訣竅是你的輸入和輸出sid是第一列,所以你必須將這兩者結合在一起才能得到正確的組合......從那裏得到一個簡單的總數。

SELECT sid, cid, SUM(counting) FROM 
(
    SELECT cid, enter_sid as sid, COUNT(*) as counting FROM record GROUP BY enter_sid 
    UNION ALL 
    SELECT cid, exit_sid as sid, COUNT(*) as counting FROM record GROUP BY exit_sid 
)t 
GROUP BY sid 

Working Fiddle