mysql统计非空字段

标签 mysql

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

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

  2. 对于给定的 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/

相关文章:

php - 如何正确使用like系统twitter风格的按钮

mysql - isValid() 调用永远不会在 MySQL JDBC 连接上返回

php - 如何从MySQL表中随机选择行

mysql - 如何编码日期以在 mysql 中进行高效查询

php - 如何确认房间是否已满?

mysql - 复杂SQL排名查询

mysql - 如何根据列的顺序添加自增主键?

mysql存储过程跳过空参数

mysql - select ifnull() 不会让查询中超过 1 列

php - mysql_fetch_assoc() : supplied argument is not a valid MySQL result resource