如何从sql server中选择年份的月份数据

时间:2015-03-02 09:47:38

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

我有一个用户表,数据大约有20年的历史。 我想从CreatedOn列(2014-07-08 17:44:00)获取月度数据,如果数据在任何月份都没有,那么本月我想要0

示例

Month   data    year

jan      34     2014

feb      56     2014

march    0      2014

apr      23     2014

我正在使用以下查询,但它无效

with cte(monno , monname ) as(
select 1, 'Jan' union all 
select 2, 'Feb' union all 
select 3, 'Mar' union all 
select 4, 'Apr' union all 
select 5, 'May' union all 
select 6, 'Jun' union all 
select 7, 'Jul' union all 
select 8, 'Aug' union all 
select 9, 'Sep' union all 
select 10, 'Oct' union all 
select 11, 'Nov' union all 
select 12, 'Dec' 
)

select distinct monname,monno,
count(CreatedOn) over(partition by datepart(year,CreatedOn),DATEPART(MONTH,CreatedOn))
from Contributors_tbl a 
right join cte b on DATEPART(MONTH,CreatedOn) = b.monno and datepart(year,CreatedOn) = 2014
order by monno

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

尝试这种方式查找月份编号和月份名称

    CREATE TABLE #TempMonth
    (
        MonthNum int,
        MonthNames varchar(50)
    )

    INSERT INTO  #TempMonth 
    SELECT STR(MONTH(DATEADD(mm, number, GETDATE())), 2) AS MonthNum, 
    DATENAME(month, DATEADD(month, MONTH(DATEADD(mm, number, GETDATE())), 0) - 1) AS MonthNames
    FROM master.dbo.spt_values
    WHERE (name IS NULL) AND (number BETWEEN 0 AND 11) ORDER BY STR(MONTH(DATEADD(mm, number, GETDATE())), 2)


    SELECT * FROM #TempMonth

    select distinct MonthNames,MonthNum,
    count(CreatedOn) over(partition by datepart(year,CreatedOn),DATEPART(MONTH,CreatedOn))
    from Contributors_tbl a 
    right join #TempMonth b on DATEPART(MONTH,CreatedOn) = b.MonthNum and datepart(year,CreatedOn) = 2014
    order by MonthNum

    DROP Table #TempMonth

答案 1 :(得分:0)

试试这个

with cte(monno , monname ) as(
select 1, 'Jan' union all 
select 2, 'Feb' union all 
select 3, 'Mar' union all 
select 4, 'Apr' union all 
select 5, 'May' union all 
select 6, 'Jun' union all 
select 7, 'Jul' union all 
select 8, 'Aug' union all 
select 9, 'Sep' union all 
select 10, 'Oct' union all 
select 11, 'Nov' union all 
select 12, 'Dec' 
)
select monname,
monno,
coalesce(cnt,0) as cnt
from cte c
outer apply (
select count(*) as cnt
from Contributors_tbl 
where CreatedOn >= DATEADD(mm,c.monno - 1,'20140101')
And CreatedOn < DATEADD(mm,c.monno,'20140101')
)t
order by monno