在表 members(id, contractid, a,b,c,d)
中,我需要计算:
至少拥有 a,b,c,d>0 之一的成员数
对于给定的 contractid,a>0、b>0 等的行数(契约(Contract)和成员之间的关系是一对多)。
我的目标是显示一个图表(表格),其中包含关于有多少成员在他们的契约(Contract)中选择了 a、b、c 和 d 的分组信息。
最佳答案
通过将聚合 SUM()
与返回 0 或 1 的 bool 测试结合使用,您可以确定填充了多少:
至少有一个填写的成员数:
SELECT COUNT(*)
FROM members
/* add up the boolean comparisons (which return 0 or 1) to find out if the total is > 0 */
WHERE ((a > 0) + (b > 0) + (c > 0) + (d > 0)) > 0
/* Actually that's overkill, and it could just be an OR chain */
/* WHERE a > 0 OR b > 0 OR c > 0 OR d > 0 */
每个合约编号
SELECT
contractid,
/* SUM() a 1 for each row in which the col is > 0 */
SUM(CASE WHEN a > 0 THEN 1 ELSE 0 END) AS a_greater_than_0,
SUM(CASE WHEN b > 0 THEN 1 ELSE 0 END) AS b_greater_than_0,
SUM(CASE WHEN c > 0 THEN 1 ELSE 0 END) AS c_greater_than_0,
SUM(CASE WHEN d > 0 THEN 1 ELSE 0 END) AS d_greater_than_0
FROM members
GROUP BY contractid
MySQL 允许您缩短它,因为 (a > 0)
返回 1 或 0,但这不能移植到所有其他 RDBMS:
SELECT
contractid,
/* SUM() a 1 for each row in which the col is > 0 */
SUM(a > 0) AS a_greater_than_0,
SUM(b > 0) AS b_greater_than_0,
SUM(c > 0) AS c_greater_than_0,
SUM(d > 0) AS d_greater_than_0
FROM members
GROUP BY contractid
关于mysql统计非空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11124520/