【问题标题】:SQL how to count the number of credit cards that had x transactions per monthSQL如何计算每月有x笔交易的信用卡数量
【发布时间】:2015-06-24 10:55:07
【问题描述】:

我有一个信用卡交易的 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 |

我不知道如何在这个数据集中按月分组。

【问题讨论】:

  • 内部查询select year(transdate), month(transdate) ... group by year, month,然后在外部查询中进行同样的分组
  • 我试过了,但是 sum(cnt >= 1) 等会加起来整个数据集,不管月份。
  • 那么您没有对外部结果进行分组。两个查询都需要group by year,month

标签: mysql sql group-by grouping derived-table


【解决方案1】:

如果您想要每月的值,那么您需要在内部和外部查询中按月聚合:

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;

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 2015-06-23
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多