mysql - SQL如何计算每月有x笔交易的信用卡数量

标签 mysql sql group-by grouping derived-table

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

关于mysql - SQL如何计算每月有x笔交易的信用卡数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29701745/

相关文章:

用于服务器通知的 Android 客户端监听器

mysql 从一个表中选择所有内容并检查另一表的 ID 和状态

sql - Nodejs Mysql Insert 向字符串添加反斜杠并失败

sql - 如何检查数据库中是否存在动名词关系并且有效

vb.net - 使用 linq vb.net 进行分组和计数

mysql - Laravel ORM 列表 groupBy 相关记录

mysql - 删除查询抛出 : Error 1062 Duplicate entry 'X-Y' for key; but no duplicates in table

mysql - 环回自定义查询未给出响应

mysql - 在mySQL中获取按 "row id"排序的SELECT结果

python - 如何将 Panda 中的多重索引更改为列