在表members(id, contractid, a,b,c,d)
中,我需要计算:
至少拥有a,b,c,d> 0
给定contractid的> 0,b> 0等的行数(合同和成员之间的关系是一对多)。
我的目标是显示一个图表(表格),其中包含有多少成员在合同中选择了a,b,c和d的分组信息。
答案 0 :(得分:2)
通过将聚合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
答案 1 :(得分:0)
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;