SQL Server查询将花费的夜晚分成相应的“月”列

我正在使用SQL Server 2012,我需要编写一个查询,它将分割到达日期和出发日期之间的差异(即,花费的夜晚数量),并将结果发布到其各自的月份列中.

我已经知道如何编写将获取我的到达日期和离开日期的查询,但它是分裂部分,对我来说是最困难的部分.我的最终结果需要看起来像这样:

ID    Name       Date of Arrival    Date of Departure   Jan  Feb  Mar  Apr
203   Mr Smith   2014.02.24         2014.03.02                5    1    
455   Mr Jones   2014.04.10         2014.04.17                          7

身份证,姓名,抵达日期和出发日期来自特定的表格.如何将拆分部分添加到现有查询中,以使输出如上所示?

在做了一些研究之后,我注意到Calendar表可能有一些帮助,但我不知道如何在我的查询中实现它.

感谢您的投入.

最佳答案 我认为Calendar表将是最佳选择.我认为查询看起来像这样,我将你的表命名为VisitDate,并假设Calendar表有一个Date字段和一个Month字段.

select ID, Name, [DATEADD of Arrival], [DATEADD of Departure], 
    sum(case when c.month = 1 then 1 else 0 end) as Jan, 
    sum(case when c.month = 2 then 1 else 0 end) as Feb, 
    sum(case when c.month = 3 then 1 else 0 end) as Mar, 
    sum(case when c.month = 4 then 1 else 0 end) as Apr 
from 
    VisitDate
    join Calendar c on c.Date >= [DATEADD of Arrival] and c.Date <= [DATEADD of Departure]
点赞