老龄化报告30,60,90以上

时间:2016-11-29 12:12:47

标签: sql-server

我试着数不了。 30,60至90天之间收到的账单。

这是我的T-SQL查询:

SELECT 
    costcentreid,
    'Current' = CASE  
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) < 30 
                      THEN COUNT(PVNo) 
                END, 
    '30_days' = CASE 
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) BETWEEN 30 AND 60  
                      THEN COUNT(PVNo) 
                END, 
    '60_days' = CASE 
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) BETWEEN 60 AND 90 
                      THEN COUNT(PVNo) 
                END, 
    '90_plus' = CASE 
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) > 90 
                      THEN COUNT(PVNo) 
                END
FROM  
    SPRGMMS..PVRegister
GROUP BY 
    CostCentreId

当我运行时,我收到错误:

  

Msg 8120,Level 16,State 1,Line 2
  列'[DB] .. PVRegister.BillDate'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

请帮助

2 个答案:

答案 0 :(得分:2)

您需要外部聚合

SELECT 
    costcentreid,
    COUNT(CASE  
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) < 30 
                      THEN PVNo
                END) as 'Current', 
    COUNT(CASE 
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) BETWEEN 30 AND 60  
                      THEN PVNo
                END) as '30_days', 
    COUNT(CASE 
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) BETWEEN 60 AND 90 
                      THEN PVNo 
                END) as '60_days', 
    COUNT(CASE 
                   WHEN DATEDIFF(DAY, BillDate, Getdate()) > 90 
                      THEN PVNo
                END) as '90_plus'
FROM  
    SPRGMMS..PVRegister
GROUP BY CostCentreId

答案 1 :(得分:0)

SELECT
    costcentreid,
    SUM(CASE WHEN d = 1 THEN 1 ELSE 0 END) AS '30_days'
    SUM(CASE WHEN d = 2 THEN 1 ELSE 0 END) AS '60_days',
    SUM(CASE WHEN d = 3 THEN 1 ELSE 0 END) AS '90_days',
FROM (
    SELECT PVNo, costcentreid, DATEDIFF(DAY, BillDate, Getdate())) / 30 AS d FROM SPRGMMS..PVRegister
) T
WHERE d <= 3
GROUP BY costcentreid