如何从两个月份获得月度报告?

时间:2015-01-29 04:06:02

标签: c# sql-server

我有一个名为Leave它包含2行的表

no=1 Leave=CL,Lnumber=2,FromDate='2015-01-10',ToDate=2015-01-11'
no=2 Leave=CL,Lnumber=2,FromDate='2015-01-12',ToDate=2015-01-13'
no=3 Leave=CL,Lnumber=2,FromDate='2015-01-15',ToDate='2015-02-16'
no=4 Leave=CL,Lnumber=2,FromDate='2015-01-31',ToDate='2015-02-01'

在这里,我想获得1月份的休假报告(离开和Lnumer)。考虑到FromDate和ToDate,我怎样才能获取这个 答案应该是这样的

Leave=CL,Lnumber=7 (for jan month)
Leave=Cl,Lnumber=1 (for feb month)

我正在使用MSSQL 2008.如果有必要,您可以添加额外的字段。谢谢

1 个答案:

答案 0 :(得分:1)

我建议建立一个日历表(基本上是一个计数表,但有日期)。然后将您的请假表加入到日期和日期之间的日历表中,并计算该时间间隔内的日期。

;with t as
(
    select no=1, Leave='CL',Lnumber=2,FromDate=cast('2015-01-10' as date),ToDate=cast('2015-01-11' as date) union all
    select no=2, Leave='CL',Lnumber=2,FromDate=cast('2015-01-31' as date),ToDate=cast('2015-02-01' as date)
), cal as
(
    select top 10000 _date = cast(cast(row_number() over (order by (select null)) + 41000 as datetime) as date)
    from sys.objects a, sys.objects b
)
select 
    t.Leave,
    _year = datepart(year, c._date), 
    _month = datepart(month, c._date),
    count(_date)
from t
inner join cal c
    on c._date between t.FromDate and t.ToDate
group by t.Leave, datepart(year, c._date), datepart(month, c._date)