SQL Server查询每月总计

时间:2010-09-26 01:00:52

标签: sql-server totals

我有一个查询,总计了所有在01/01/2010上有效的案例。

SELECT     COUNT(CaseID) AS Total
FROM         dbo.ClientCase
WHERE     (CaseStartDate <= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) AND (CaseClosedDate >= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) OR (CaseClosedDate IS NULL)
GROUP BY CaseStartDate

我还有一个Calendar表,可用于创建一个查询,从1月1日,2月1日,3月1日到12月1日返回12个日期。

我无法弄清楚如何结合2个查询,因此我得到了每个月1日的所有案例总数的计数。

我需要看到像

这样的东西
Month   Total
Jan     102
Feb     130
Mar     145
.....
Dec     162

3 个答案:

答案 0 :(得分:5)

SELECT cal.MonthName, COUNT(CaseID) AS Total 
FROM dbo.calendarTable cal
LEFT OUTER JOIN dbo.ClientCase cc
ON Month(cal.MonthStartDate) = Month(CaseStartDate)
WHERE 
(CaseStartDate <= CONVERT(DATETIME, cal.MonthStartDate, 102)) AND 
(CaseClosedDate >= CONVERT(DATETIME, cal.MonthStartDate, 102)) OR 
(CaseClosedDate IS NULL) 
GROUP BY cal.MonthName
  • 左外连接以确保您获得所有月份,包括0个案例

答案 1 :(得分:2)

假设日历有两列,例如MonthNameFirstDate,您需要s / like

SELECT Calendar.MonthName AS Month, COUNT(ClientCase.CaseId) AS Total,
  FROM ClientCase
  JOIN Calendar
    ON (MONTH(Calendar.FirstDate) = MONTH(ClientCase.CaseStartDate))
  GROUP BY Calendar.MonthName

答案 2 :(得分:1)

您只需按查询的月份进行分组:

SELECT
    MONTH(CaseStartDate), COUNT(CaseID) AS Total
FROM         
    dbo.ClientCase
WHERE     
    (CaseStartDate <= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) 
    AND (CaseClosedDate >= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) OR 
        (CaseClosedDate IS NULL)
GROUP BY 
    MONTH(CaseStartDate)

这应该会给你一个非常接近的输出(数月而不是1月,2月等 - 但足够接近)。

通过这个额外步骤,您将获得每个月名称的前三个字母:

SELECT
    SUBSTRING(DATENAME(MONTH, CaseStartDate), 1, 3) AS 'Month', 
    COUNT(CaseID) AS Total
FROM         
    dbo.ClientCase
WHERE     
    (CaseStartDate <= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) 
    AND (CaseClosedDate >= CONVERT(DATETIME, '2010-01-01 00:00:00', 102)) OR 
        (CaseClosedDate IS NULL)
GROUP BY 
    MONTH(CaseStartDate), SUBSTRING(DATENAME(MONTH, CaseStartDate), 1, 3)
ORDER BY
    MONTH(CaseStartDate)