从同一张表中选择两个不同的计数总和

时间:2019-05-16 11:46:47

标签: mysql sql count aggregate-functions

我有一张下表:

id  | R_ID  | is_assigned
-----------------
1   | X1    | 1
2   | X1    | 0
3   | X1    | 0
4   | X1    | 0

我想获得两个不同的COUNT()值:一个属于group X1的所有行的值。接下来是属于group X1are not assigned, i.e. is_assigned value 0的行。

输出:

R_ID  | Total Records  | Remaining
----------------------------------
X1    | 4              | 3

据我所知:

SELECT t1.r_id, COUNT(t1.*) as total_records
FROM tasks t1
GROUP BY r_id

如何获得另一个count

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合。我建议在MySQL中这样写:

SELECT t1.r_id, COUNT(*) as total_records,
       SUM(t1.is_assigned = 0) as remaining
FROM tasks t1
GROUP BY t1.r_id