2015-04-17 58 views
1

X交易的信用卡數量:SQL怎麼算我的信用卡交易的MySQL數據集,有每月

create table trans (
    transdate date, 
    card_id int 
); 

我渴望知道:

1. how many cards were used to make at least 1 transaction, per month 
2. how many cards were used to make at least 5 transactions, per month 
3. how many cards were used to make at least 10 transactions, per month 
4. how many cards were used to make at least 20 transactions, per month 
etc... 

因爲團體重疊,看來有條件的聚合是一種更好的辦法:

select sum(cnt >= 1) as trans_1, 
     sum(cnt >= 5) as trans_5, 
     sum(cnt >= 10) as trans_10, 
     sum(cnt >= 20) as trans_20 
from (select card_id, count(*) as cnt 
     from trans 
     group by card_id 
    ) d; 

問題是上面產生的結果集合。我想結果每月設置

year | month | trans_1 | trans_5 | trans_10 | trans_20 | etc 
2015 |  1 |  1 |  1 |  0 |  0 | 
2015 |  2 | 
2015 |  3 | 

我無法弄清楚如何按月份該數據集組。

+0

內部查詢'選擇年份(transdate),月(transdate)... GROUP BY年,月「,然後在外部查詢 –

+0

相同的分組,我試過,但總和(cnt> = 1)等將加起來整個數據集無論月份。 – davidjhp

+0

然後你沒有將外部結果分組。您需要在兩個查詢中按年份,月份分組 –

回答

2

如果你想每個月的值,那麼你需要在一個月內,外查詢彙總:

select yr, mon, 
     sum(cnt >= 1) as trans_1, 
     sum(cnt >= 5) as trans_5, 
     sum(cnt >= 10) as trans_10, 
     sum(cnt >= 20) as trans_20 
from (select year(transdate) as yr, month(transdate) as mon, card_id, count(*) as cnt 
     from trans 
     group by card_id, year(transdate), month(transdate) 
    ) d 
group by yr, mon;