sql-一个包含两个日期列的表数数并加入

bt1cpqcv  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(275)

我有一个表(vokpi\u tickets),它包含以下列:
|创建日期|完成日期|
我想对每一列进行计数,并按日期对它们进行分组。完成后应该是这样的:
|日期|创建计数|计数完成|
我可以通过这样的操作分别获得每个计数:

SELECT COUNT(TicketId)
FROM vOKPI_Tickets
GROUP BY CreationDate

SELECT COUNT(TicketId)
FROM vOKPI_Tickets
GROUP BY CreationDate

如何将输出合并到一个表中?我还要指出,这将成为一种看法。
提前谢谢

zlwx9yxi

zlwx9yxi1#

简单通用方法:

select
coalesce(crte.creationdate, cmpl.CompletionDate) as theDate,
crte.cnt as created,
cmpl.cnt as completed
from
(select creationdate, count (*) as cnt from vOKPI_Tickets where creationdate  is not null group by creationdate) crte
full join
(select CompletionDate, count (*) as cnt from vOKPI_Tickets where CompletionDate  is not null group by CompletionDate) cmpl
on crte.creationdate  = cmpl.CompletionDate
jum4pzuy

jum4pzuy2#

可以取消拆分和聚合。一般方法是:

select dte, sum(created), sum(completed)
from ((select creationdate as dte, 1 as created, 0 as completed
       from vOKPI_Tickets
      ) union all
      (select completed as dte, 0  created, 1 as completed
       from vOKPI_Tickets
      ) 
     ) t
group by dte;
xmakbtuz

xmakbtuz3#

在sql server中,可以使用 cross apply 为此:

select d.dt, sum(d.is_completed) count_created, sum(d.is_completed) count_completed
from vokpi_tickets t
cross apply (values (creationdate, 1, 0), (completion_date, 0, 1)) as d(dt, is_created, is_completed)
where d.dt is not null
group by d.dt

相关问题