我试图找到谁收到1/2/3邮箱从下表的独特客户的计数:

cust_id month email_cnt
1 202311 1
1 202311 1
1 202310 1
1 202310 0
1 202309 1
2 202311 0
2 202311 0
2 202310 0
2 202310 1
2 202309 1
3 202311 0
3 202311 1
3 202310 0
3 202310 0
3 202309 1

这是所需的输出,将每月的邮箱数相加后,计算收到x封邮箱的唯一客户的数量:

month cust_with_1email cust_with_2email cust_with_3email
202311 2 1 0
202310 2 0 0
202309 3 0 0

我正在try 使用CASE函数,但没有成功:

SELECT distinct month, 
SUM(case when email_cnt = 1 then email_cnt end) cust_with_1email, 
SUM(case when email_cnt = 2 then email_cnt end) cust_with_2email, 
SUM(case when email_cnt = 3 then email_cnt end) cust_with_3email
FROM mytable
GROUP BY month

推荐答案

我还是不能重现你的结果.

WITH CTE as (SELECT
cust_id, month, SUM(email_cnt) email_cnt
FROM mytable
GROUP BY cust_id, month)
SELECT month, 
SUM(case when email_cnt = 1 then email_cnt ELSE 0 end) cust_with_1email, 
SUM(case when email_cnt = 2 then email_cnt ELSE 0  end) cust_with_2email, 
SUM(case when email_cnt = 3 then email_cnt ELSE 0  end) cust_with_3email
FROM CTE
GROUP BY month
month cust_with_1email cust_with_2email cust_with_3email
202311 1 2 0
202310 2 0 0
202309 3 0 0

至少会给你一个确定性的结果

Sql相关问答推荐

用于动态查询情况的存储过程常识模式

在Golang中管理数据库事务的简洁方法

如何使用ROW_NUM() Select 一个没有第二条记录的实例?

如何在SQL中更新Json字符串

PostgreSQL 9.6嵌套的INSERT/RETURN语句的CTE性能低得令人无法接受

如何将`now()`作为SQL插入语句的一部分?

在迁移到.NET8后,使用Array.Containers的F#查询表达式失败

根据时间、状态和相关行在PostgreSQL中的存在来删除行

存储过程太慢

如何修复初学者 SQL INNER JOIN 查询错误

验证某个日期前后的连续代码

PostgreSQL 中将数据从 JSONB 类型转换为 Array 类型

获取记录的上一个值,并将其与当前值一起显示

MariaDB非常简单的MATCHAGAINST查询不使用FULLTEXT索引吗?

Postgres数据库维护:基于GROUP BY删除旧记录

多行状态下的分组查询判断状态

获取 SQL Server 中每一行的两个-之间的文本

使用日期和间隔作为键加入 Athena 上的表?

在 postgresql 中,我可以将其组合成一个查询吗?

删除具有相同 ID 的重复记录 - Postgresql