SQL - 一个 Table 有两个日期列。计数并加入

SQL - One Table with Two Date Columns. Count and Join

我有一个 table (vOKPI_Tickets),其中包含以下列:

|CreationDate | CompletionDate|

我想对每一列进行计数,并按日期对它们进行分组。完成后应该看起来像这样:

| Date | Count-Created | Count-Completed |

我可以单独获取每个计数,方法如下:

SELECT COUNT(TicketId)
FROM vOKPI_Tickets
GROUP BY CreationDate

SELECT COUNT(TicketId)
FROM vOKPI_Tickets
GROUP BY CreationDate

如何将输出合并为一个 table?我还应该注意到,这将成为一个视图。

提前致谢

您可以逆透视和聚合。一个通用的方法是:

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;
  

在SQL服务器中,你可以使用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

简单的通用方法:

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