我试图在一个表格中获取两个单独的数据列。
我有一个跟踪问题的数据库,一个表Issue,有两个相关的列,每个列都包含一个日期。与以下内容非常相似。
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
答案 0 :(得分:3)
这样做的一种方法是使用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
答案 1 :(得分:1)
试试这个
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
答案 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;