在子查询中分组

时间:2015-09-17 07:15:41

标签: sql tsql group-by subquery

嗨,我有下面的代码,它通过到期和完整以及日期来计算总数。但是我想按日期总结一下,请有人帮忙吗?

        SELECT  CONVERT(varchar(15), GRLastDt, 111) as Date_,      
                (
                    SELECT        COUNT(*) AS Expr1
                    FROM            dbo.AN_Admin_VendorReturns_090_Final
                    WHERE        (Complete = 'X') AND (CONVERT(varchar(15), GRLastDt, 111) >= GETDATE() - 60)
                ) AS Complete,
                (
                    SELECT        COUNT(*) AS Expr1
                    FROM            dbo.AN_Admin_VendorReturns_090_Final AS AN_Admin_VendorReturns_090_Final_1
                    WHERE        (Complete <> 'X') AND (CONVERT(varchar(15), GRLastDt, 111) >= GETDATE() - 60)
                )  AS DUE

                    FROM            dbo.AN_Admin_VendorReturns_090_Final
        group by CONVERT(varchar(15), GRLastDt, 111)

1 个答案:

答案 0 :(得分:2)

SELECT  CGRLastDt as Date_,    
SUM(CASE WHEN Complete = 'X' Then 1 Else 0 END)   AS Complete,
SUM(CASE WHEN Complete <> 'X' Then 1 Else 0 END)   AS Due
FROM dbo.AN_Admin_VendorReturns_090_Final
WHERE GRLastDt >= GETDATE() - 60
GROUP BY GRLastDt

请注意,我没有验证此SQL的语法,并在记事本中执行此操作。