sql - 计算值大于或等于 SQL 中另一列的值的行数

标签 sql database aggregate-functions aggregation

我有一个包含两列的表格:一对 id 和一些“标记” 夫妻。我想要一个结果,其中列出了带有 x 标记的夫妇的数量 对于 x 的每个值,或更多。所以我的输入看起来像:

| couple_id | num_marks |
|-----------+-----------|
|         9 |         7 |
|         6 |         6 |
|         8 |         6 |
|         2 |         5 |
|         3 |         4 |
|         5 |         4 |
|         1 |         3 |
|         4 |         3 |
|        10 |         2 |
|         7 |         1 |

And I'd like to get the result:

| num_marks | num_couples |
|-----------+-------------|
|         7 | 1           |
|         6 | 3           |
|         5 | 4           |
|         4 | 6           |
|         3 | 8           |
|         2 | 9           |
|         1 | 10          |

I.e. there was 1 couple with 7 or more marks, 3 couples with 6 or more marks, 4 couples with 5 or more marks, etc. I've been able to come up with a query to return the number of couples with exactly n marks:

SELECT num_marks,
       count(couple_id) AS num_couples
  FROM table_name
  GROUP BY num_marks
  ORDER BY num_marks DESC;

产生:

| num_marks | num_couples |
|-----------+-------------|
|         7 |           1 |
|         6 |           2 |
|         5 |           1 |
|         4 |           2 |
|         3 |           2 |
|         2 |           1 |
|         1 |           1 |

即有 1 对 7 分,2 对 6 分,1 对 5 等。是 有一种方便的方法可以有效地将每一行的值与上面的值相加 它?我可以在应用程序级别做到这一点,但它似乎是那种东西 真正属于数据库。

最佳答案

这可能不是特别有效,但应该可以完成工作:

SELECT t1.num_marks,       
  (SELECT count(t2.couple_id)
   FROM table_name t2  
   WHERE t2.num_marks >= t1.num_marks
   ) AS num_couples 
FROM table_name t1  
GROUP BY t1.num_marks   
ORDER BY t1.num_marks DESC;

编辑: 您可以使用 sub query在查询的 select、from、where、group by 和 having 子句中,如果您引用主/外部“查询”,那么它将评估每一行的子查询,然后它被称为 correlated subquery . (因此关于性能的警告)

根据 Damien 的回答,您还可以使用 CTE - CTE 可以提高可读性,还可以使 IMO 的递归和自连接更容易。

大多数 SQL 都支持 AFAIK 子查询。

关于sql - 计算值大于或等于 SQL 中另一列的值的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8516502/

相关文章:

sql - 根据临时列加入

mysql - 如何使用子查询显示来自多个表的列名

sql - PostgreSQL HAVING 子句

PostgreSQL:子查询上的聚合表达式

标签系统的 MySQL 模式和 CRUD 查询

sql-server - SQL Server 中标量、表值和聚合函数之间的区别?

mysql卡在查询中

sql - 如何正确处理查询约束中的日期

mysql - 按两个值分组

mysql - Sequelize 多个数据库,通用模型名称