我有一个包含3个字段的表(tbl):id,date和status。表中的示例信息可能如下所示:
id date status
1 8-20 open
2 8-20 open
3 8-20 closed
4 8-21 closed
5 8-22 open
6 8-23 open
7 8-24 closed
我想编写一个返回数据的查询,如下所示:
date open closed
8-20 2 1
8-21 0 1
8-22 1 0
8-23 1 0
8-24 0 1
我可以得到的最接近的是在另一个选择中包含两个联合选择,如下所示:
select date from (
select date, count(id) from tbl where status = 'open' group by date
union
select date, count(id) from tbl where status = 'closed' group by date)
group by date
我认为它会涉及一个完整的外部联接,如果它不是SQLite来解释其中一个状态有0个条目但我不知道如何构造两个左连接的日子获得理想的结果。
答案 0 :(得分:1)
运行以下查询:
select date, sum(case when status ='open' then 1 else 0 end) as open from test group by date
并为关闭做同样的事。
答案 1 :(得分:0)
您可以使用相关子查询:
SELECT date,
(SELECT COUNT(*)
FROM tbl AS t2
WHERE t2.date = tbl.date
AND status = 'open'
) AS open,
(SELECT COUNT(*)
FROM tbl AS t2
WHERE t2.date = tbl.date
AND status = 'closed'
) AS closed
FROM tbl
或者,按日期分组,并计算组中具有所需状态的行数:
SELECT date,
total(status = 'open') AS open,
total(status = 'closed') AS closed
FROM tbl
GROUP BY date