我有两个表(让我们称之为案例和用户)结构如下:案例
ID|status |user_id
__|____________|_______
1 |Open |6
2 |Closed |9
3 |Incomplete |9
用户:
ID|
__|_____
6|
9|
我想选择id的计数以及每个状态字段的计数。
目前我尝试过:
SELECT COUNT(c.id), COUNT(
(SELECT status from cases where status = 'Open')),
COUNT(
(SELECT status from cases where status = 'Closed')),
COUNT(
(SELECT status from cases where status = 'Incomplete'))
FROM cases as c
JOIN users as u on u.id = c.user_id
我收到错误的查询返回多行。
这就是我想要实现的目标
ID| Open | Closed | Incomplete |user_id
__|______|________|____________|__________
2|0 |1 |1 |9
RECAP:每个用户ID的计数,用于计算ID的数量和每个状态的计数。
答案 0 :(得分:3)
您可以使用sum
SELECT COUNT(c.id),
SUM(c.status = 'Open') Open ,
SUM(c.status = 'Closed') Closed ,
SUM(c.status = 'Incomplete') Incomplete,
u.id user_id
FROM cases as c
JOIN users as u on u.id = c.user_id
GROUP BY u.id