sql 日期类型的条件聚合函数

sql conditional aggregate function with date type

我table喜欢:

    CREATE TABLE myissues 
        (
         id int IDENTITY(1,1) primary key, 
         title varchar(20), 
         status varchar(30),
         submitdate datetime,
         updatedate datetime
        );

    INSERT INTO myissues
    (title, status,submitdate,updatedate)
    VALUES
    ('issue1', 'closed','2014-01-01 07:59:59.000','2014-01-02 10:59:59.000'),
    ('issue2', 'closed','2014-01-01 08:59:59.000','2014-01-02 12:59:59.000'),
    ('issue3', 'closed','2014-01-01 09:59:59.000','2014-01-02 10:59:59.000'),
    ('issue4', 'closed','2014-01-02 07:59:59.000','2014-01-03 10:59:59.000'),
    ('issue5', 'closed','2014-01-02 08:59:59.000','2014-01-03 11:59:59.000'),
    ('issue6', 'closed','2014-01-03 08:59:59.000','2014-01-03 12:59:59.000');

我想获得每天的问题计数,计数应该分为两个不同的类别:已提交的未解决问题和已关闭的问题,即状态='closed' 和更新日期。 这是我的 sql 脚本:

SELECT 
    convert(nvarchar(10),submitdate,112) as Dates, 
    COUNTS_OPEN   = SUM(case when (submitdate > CONVERT(datetime, '2014-01-01 00:00:00.000') and submitdate < CONVERT(datetime, '2014-01-05 00:00:00.000') ) then 1 else 0 end), 
    COUNTS_CLOSED = SUM(case when (status='closed' and (updatedate > CONVERT(datetime, '2014-01-01 00:00:00.000') and updatedate < CONVERT(datetime, '2014-01-05 00:00:00.000')) ) then 1 else 0 end) 
FROM myissues
GROUP BY convert(nvarchar(10),submitdate,112)
order by convert(nvarchar(10),submitdate,112)

sqlfiddle 中的结果是:

DATES   COUNTS_OPEN COUNTS_CLOSED
20140101    3            3
20140102    2            2
20140103    1            1

如您所见,COUNTS_CLOSED 的结果是错误的。对于上面列出的日期,正确的结果应该是 0、3、3。 我想我没有正确分组。有人可以帮忙吗?

谢谢!

您需要将关闭计数与主查询分开。试试这个。 ..

SELECT convert(nvarchar(10),submitdate,112) as Dates, 
COUNTS_OPEN   = COUNT(1), 
COUNTS_CLOSED = (SELECT COUNT(1) FROM myissues f WHERE f.status = 'closed' AND  convert(nvarchar(10),updatedate,112) = convert(nvarchar(10), m.submitdate,112))
FROM myissues m
GROUP BY convert(nvarchar(10),submitdate,112)
order by convert(nvarchar(10),submitdate,112)

请注意,如果问题在没有提交问题的那一天关闭,则此查询将无效。要正确执行此操作,您需要获得详尽的日期列表。

尝试这样的事情...

SELECT m.Dates, 
COUNTS_OPEN = (SELECT COUNT(1) FROM myissues f WHERE convert(nvarchar(10),submitdate,112) = m.Dates),
COUNTS_CLOSED = (SELECT COUNT(1) FROM myissues f WHERE f.status = 'closed' AND  convert(nvarchar(10),updatedate,112) = m.Dates)
FROM (
    SELECT convert(nvarchar(10),submitdate,112) as Dates
    FROM myissues
    UNION
    SELECT convert(nvarchar(10),updatedate,112)
    FROM myissues
) m
order by m.Dates