开发者

Count by day, count by week, in a grouped select statement

I am trying to count instances of a status by current day and current week, grouped by town.

(The table has just 3 columns: 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

This code just returns a month count for both day total and week total columns

Hope you can help.


I surgest you do this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜