我正在尝试按当前日期和当前周计算状态的实例,按城镇分组。
(该表只有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
此代码仅返回日总计和周总列数的月份计数
希望你能提供帮助。
答案 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