1

我有一个名为的表tours,其中有以下字段

tourId, tourStartDate, tourEndDate , tourDetail ,deptCode,targetYear, and officerName

现在我想把我的数据总结成几个月,所以结果表应该像下面的模式

declare @temp table (
  id int identity(1,1) not null,
  officerName, 
  jan int ,feb int,
  march int,april int, 
  may int,
  june int ,
  july int, 
  aug int,
  sep int, 
  oct int, 
  nov int, 
  dec int
);
select * from  @temp

我尝试with cte遍历每一行并使用 case 插入临时表,但它看起来不是很好的解决方案,所以任何线索或指南都对我有很大帮助。

该月官员完成的旅行计数将作为值显示在月份列中

已编辑

开始日期在 1 月,结束日期在其他月份的巡演,比如说 2 月,那么它的值将出现在两个月

4

2 回答 2

2

为了使它出现在两个月中,如果 end 在不同的月份,则将 (1) 按开始日期 (2) 按结束日期的查询部分联合起来。要比较月份,请使用MONTH获取日期的月份。

要将列名称作为月份,请使用DateName (Month, )。为了使其保持一致,请使用LEFT仅使用前 3 个字符。

要将行转换为列,请使用PIVOT

SELECT officerName, Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
FROM (
    select LEFT(datename(month,tourStartDate),3) mon, officerName
    from tbl
    union all
    select LEFT(datename(month,tourEndDate),3) mon, officerName
    from tbl
    where month(tourStartDate) != month(tourEndDate)
) P
PIVOT (COUNT(mon) for mon in (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)) PV
于 2012-10-01T12:51:34.887 回答
2

您正在寻找一个pivot

http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

就像是

select *
from  (select officername, month(tourstartdate) tsm, value from tours) src
pivot 
(sum(value) for tsm in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) p
于 2012-10-01T12:37:20.907 回答