按日计算,按周计算,在分组的选择语句中

时间:2011-06-21 10:54:19

标签: sql sql-server tsql

我正在尝试按当前日期和当前周计算状态的实例,按城镇分组。

(该表只有3列:Town,status,status_date)

SELECT 
     MAX(dbo.Clients.Town) AS Town, 
     CASE 
        WHEN MAX(datepart(wk, status_date)) = DATEPART(wk, getdate()) THEN COUNT(Town) 
        ELSE 0 
     END AS wkTotal,
     CASE 
        WHEN MAX(CONVERT(date, status_date, 106)) = CONVERT(date, getdate(), 106) THEN COUNT(Town) 
        ELSE 0 
     END AS dayTotal
FROM 
     dbo.Clients 
WHERE
     dbo.Clients.Status LIKE 'Status 1%'
     AND MONTH(GETDATE()) = MONTH(dbo.Clients.Status_date)
     AND YEAR(GETDATE())= YEAR(dbo.Clients.Status_date)
GROUP BY 
     dbo.Clients.Town
ORDER BY 
     dbo.Clients.Town

此代码仅返回日总计和周总列数的月份计数

希望你能提供帮助。

1 个答案:

答案 0 :(得分:1)

我建议你这样做:

SELECT dbo.Clients.Town AS Town, 
count(*) AS wkTotal, 
sum(CASE WHEN datepart(dayofyear, status_date) = DATEPART(dayofyear, getdate()) THEN 1 ELSE 0 END) AS dayTotal
FROM dbo.Clients 
WHERE dbo.Clients.Status LIKE 'Status 1%' AND 
datepart(week, GETDATE()) = datepart(week, dbo.Clients.Status_date)
AND YEAR(GETDATE())= YEAR(dbo.Clients.Status_date)
GROUP BY dbo.Clients.Town 
ORDER BY dbo.Clients.Town