在一张表中members(id, contractid, a,b,c,d)
,我需要计算:
至少有 a,b,c,d>0 之一的成员数
给定contractid的a>0、b>0等的行数(合约和成员之间的关系是一对多的)。
我的目标是显示一个图表(表格),其中包含关于有多少成员在他们的合同中选择了 a、b、c 和 d 的分组信息。
在一张表中members(id, contractid, a,b,c,d)
,我需要计算:
至少有 a,b,c,d>0 之一的成员数
给定contractid的a>0、b>0等的行数(合约和成员之间的关系是一对多的)。
我的目标是显示一个图表(表格),其中包含关于有多少成员在他们的合同中选择了 a、b、c 和 d 的分组信息。
通过将聚合SUM()
与返回 0 或 1 的布尔测试结合使用,您可以确定填充了多少:
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
select count(id) from Members where (a>0 or b>0 or c>0 or d>0)
select contractid,count(id) from members group by contractid having a>0;
select contractid,count(id) from members group by contractid having b>0;