SQL每月摘要

时间:2011-08-10 10:52:57

标签: sql sql-server sql-server-2008

我有一个包含每个项目的开始日期的表格

例如:

ID - Startdate
1  - 2011-01-01
2  - 2011-02-01
3  - 2011-04-01
...

我需要一个查询,它会给我每个月内每个项目的计数,我需要一个完整的12个月的报告。我试过简单地按Month(StartDate)进行分组,但是对于没有值的月份,这并没有给我一个零,在上面的例子中,为3月。

所以我希望输出符合..

Month - Count
  1      20
  2      14
  3      0
...

有什么想法吗?

感谢。

2 个答案:

答案 0 :(得分:5)

SELECT A.Month, ISNULL(B.countvalue,0) Count
FROM (SELECT 1 AS MONTH
UNION 
SELECT 2 
UNION 
SELECT 3 
UNION 
SELECT 4 
UNION 
SELECT 5 
UNION 
SELECT 6 
UNION 
SELECT 7 
UNION 
SELECT 8 
UNION 
SELECT 9 
UNION 
SELECT 10 
UNION 
SELECT 11 
UNION 
SELECT 12 ) A LEFT JOIN (SELECT datepart(month,Startdate) AS Month, Count(ID) as countvalue FROM yourTable GROUP BY datepart(month,Startdate))B
ON A.month = B.month

希望这有帮助

答案 1 :(得分:5)

使用SQL Server 2005+Oracle执行此操作的另一种方法。

SQL语句

;WITH q (Month) AS (
    SELECT  1
    UNION ALL
    SELECT  Month + 1
    FROM    q   
    WHERE   q.Month < 12
)
SELECT  q.Month
        , COUNT(i.ID)
FROM    q
        LEFT OUTER JOIN Input i ON MONTH(i.StartDate) = q.Month
GROUP BY
        q.Month

测试脚本

;WITH Input (ID, StartDate) AS (
    SELECT 1, '2011-01-01'
    UNION ALL SELECT 2, '2011-02-01'
    UNION ALL SELECT 3, '2011-04-01'
)
, q (Month) AS (
    SELECT  1
    UNION ALL
    SELECT  Month + 1
    FROM    q   
    WHERE   q.Month < 12
)
SELECT  q.Month
        , COUNT(i.ID)
FROM    q
        LEFT OUTER JOIN Input i ON MONTH(i.StartDate) = q.Month
GROUP BY
        q.Month