簡體   English   中英

使用開始日期和結束日期在月度報告中分組數據

[英]Group data in monthly report using start date and end date

我有一個名為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遍歷每一行並使用大小寫插入臨時表,但它看起來不是很好的解決方案所以任何線索或指南真的幫助了我很多。

官員在該月完成的旅行次數將在月份列中顯示為值

EDITED

一個旅游的開始日期在jan和結束日期在其他一個月,然后feb然后它的價值將在兩個月出現

你正在尋找一個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

為了使它在兩個月內出現, UNION查詢部分(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM