1

在一张表中members(id, contractid, a,b,c,d),我需要计算:

  1. 至少有 a,b,c,d>0 之一的成员数

  2. 给定contractid的a>0、b>0等的行数(合约和成员之间的关系是一对多的)。

我的目标是显示一个图表(表格),其中包含关于有多少成员在他们的合同中选择了 a、b、c 和 d 的分组信息。

4

2 回答 2

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 */

每个合约 ID 的数量

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
于 2012-06-20T17:12:25.763 回答
0
  1. select count(id) from Members where (a>0 or b>0 or c>0 or d>0)

  2. select contractid,count(id) from members group by contractid having a>0;
    select contractid,count(id) from members group by contractid having b>0;

于 2012-06-20T17:12:20.550 回答