我有一个包含两列的表格:一对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, 4couples with 5 or more marks, etc. I've been able to come up with a query toreturn 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 |

IE。有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;

编辑:
您可以在查询的select,from,where,group by和having子句中使用sub query,如果您引用主/外部“query”,则它将评估每一行的子查询,因此称为correlated subquery 。 (因此请注意性能)

根据Damien的回答,您还可以使用CTE-CTE可以提高可读性,还可以简化IMO的递归和自联接。

大多数SQL支持AFAIK子查询。

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

10-12 00:48