我有下表-案例
ID Date Created Date Resolved
1 1/1/2015
2 1/1/2015 1/1/2015
3 2/1/2015
4 1/1/2015 2/1/2015
5 4/1/2015
我必须编写一个SQL查询,该查询返回创建的案例数与每天解决的案例数 预期结果:
Day Created Resolved
1/1/2015 3 1
2/1/2015 1 1
3/1/2015 0 0
4/1/2015 1 0
我正在尝试类似的事情:
SELECT
DateCreated as Day,
COUNT(DateCreated) as Created,
DateResolved as Resolved
FROM cases
GROUP BY Day;
但是有些错误,有人可以帮助我理解我必须实现的逻辑吗?
答案 0 :(得分:2)
您应该对每个结果使用单独的查询,然后使用UNION将它们组合在一起。
尝试一下:
SELECT day, SUM(created) as created, SUM(solved) as solved FROM
(
SELECT c1.date_created as day, COUNT(c1.id) as created, 0 as solved FROM cases c1 GROUP BY c1.date_created
UNION
SELECT c2.date_solved as day, 0 as created, COUNT(c2.id) as solved FROM cases c2 WHERE c2.date_solved IS NOT NULL GROUP BY c2.date_solved
) as unionTable
GROUP BY day;
致谢!
答案 1 :(得分:1)
您可以使用union all
和group by
解决大部分问题:
select dte, sum(created), sum(resolved)
from ((select date_created as dte, 1 as created, 0 as resolved
from t
) union all
(select date_resolved as dte, 0 as created, 1 as resolved
from t
)
) t
group by dte;
这不会产生该行:
3/1/2015 0 0
因为日期不在原始数据中。有多种生成方法,具体取决于数据库。或者,您可能有一个日历表,周围摆满了您可能需要的所有日期。
编辑:
在MySQL中,我建议:
select d.dte,
(select count(*)
from t
where t.date_created = d.dte
) as created,
(select count(*)
from t
where t.date_resolved = d.dte
) as resolved
from (select date('2015-01-01') as dte union all
select date('2015-02-01') as dte union all
select date('2015-03-01') as dte union all
select date('2015-04-01') as dte
) d;
注意:对于t(date_created)
和t(date_resolved)
上的索引,这可能是最快的查询。
答案 2 :(得分:0)
您没有提及正在使用的数据库,所以我给您一个通用的答案。您可以使用FULL OUTER JOIN
来连接等式的两边。例如:
select
coalesce(c.d, r.d) as date,
c.cnt as created,
r.cnt as resolved
from (
select date(date_created) as d, count(*) as cnt
from my_table group by date(date_created)
) c
full outer join (
select date(date_resolved) as d, count(*) as cnt
from my_table group by date(date_resolved)
) r on c.d = r.d
答案 3 :(得分:0)
对于SQL Server,这是一个选项。
SELECT A.[DateCreated] [Day]
, COUNT(id) [Created]
, (SELECT COUNT( [B].[ID] ) FROM cases B WHERE B.[DateResolved] = A.[DateCreated] ) [Resolved]
FROM cases A
GROUP BY [A].[DateCreated]
这不会创建03/01/2015数据行,因为它不在初始数据集中。