按同一分组计算 2 列

Count 2 columns by the same grouping

我正在尝试在一个 table.

中获取两个独立列的数据

我有一个跟踪问题的数据库,其中一个 table,问题,有 2 个相关列,每个列都包含一个日期。与以下非常相似。

DateOpened  DateClosed
2015-01-08  2015-01-08
2015-01-08  2015-01-08
2015-01-06  2015-01-08
2015-01-06  2015-01-08
2015-01-04  2015-01-07
2015-01-02  2015-01-07
2015-01-02  2015-01-07

我的目标是能够计算每个日期打开和关闭的条目数。上面的预期输出的一个例子是。

Date          CountDateOpened CountDateClosed
2015-01-08    2               4
2015-01-07    0               3 
2015-01-06    2               0
2015-01-05    0               0
2015-01-04    1               0
2015-01-03    0               0
2015-01-02    2               0

我知道我需要按日期分组,但应该有几天关闭的问题多于打开的问题,但我的 COUNT(DateClosed) 似乎从未超过我的 Count(DateOpened)。我在查询中进行即时日期转换,但我不认为它们是相关的,因为我总是四舍五入到最近的一天。这是我目前正在运行的查询,为简单起见已进行了细化。

SELECT
    CREATEDATE AS [Date],
    COUNT(CREATEDATE) AS [Number Opened],
    COUNT(CLOSEDATE) AS [Number Closed]

FROM
     ISSUE

GROUP BY
     CREATEDATE

ORDER BY 
     [Date] DESC

一种方法是使用 union all 为两个日期创建一个列,然后根据其类型分组:

SELECT   `Date`, 
         COUNT(`open`) AS `CountDateOpened`
         COUNT(`closed`) AS `CountDateClosed`
FROM     (SELECT `DateOpened` AS `Date`, 1 AS `open`, NULL AS `closed`
          FROM   `issue`
          UNION ALL
          SELECT `DateClosed` AS `Date`, NULL AS `open`, 1 AS `closed`
          FROM   `issue`
         ) t
GROUP BY `Date`
ORDER BY `Date` DESC

试试这个

select 
 d.dt,(select COUNT(DateOpened) ct from ISSUE where
CAST(DateOpened as DATE)=CAST(d.dt as DATE) )
,(select COUNT(DateClosed) ct from ISSUE where
CAST(DateClosed as DATE)=CAST(d.dt as DATE) )
from (
select number,DATEADD(D,number-7,GETDATE()) dt
 from master.dbo.spt_values sp
where type='P' and DATEADD(D,number-7,GETDATE())<'2015-01-09'
)
d
ORDER BY d.dt desc

输出

Date      DateOpened DateClosed
2015-01-08  2            4
2015-01-07  0            3
2015-01-06  2            0
2015-01-05  0            0
2015-01-04  1            0
2015-01-03  0            0
2015-01-02  2            0

与 Mureinik 的回答相同,只是少了一些输入...

SELECT date,SUM(status='opened') opened, SUM(status = 'closed') closed 
  FROM 
     ( SELECT dateopened date,'opened' status FROM my_table
       UNION ALL
       SELECT dateclosed,'closed' FROM my_table
     ) x
 GROUP  
    BY date DESC;