如果你正在尋找一個動態透視,請考慮以下
創建一些示例數據
--Drop Table #YourTable
Create Table #YourTable (CustomerID int,StartDate date,EndDate date,SalesPersonID int,ServicePalnID int,DivisionID int)
Insert Into #YourTable values
(1,'2017-01-01','2017-02-06',1,5,1),
(2,'2017-01-01',null ,1,5,1),
(3,'2017-02-04',null ,1,5,1),
(4,'2017-02-05','2017-04-05',1,5,2),
(5,'2017-06-06',null ,2,6,2),
(6,'2017-03-26','2017-04-03',2,6,2),
(7,'2017-04-01',null ,2,6,3),
(8,'2017-04-04',null ,3,6,3)
動態查詢
Declare @Date1 date = '2017-01-01'
Declare @Date2 date = GetDate()
Declare @SQL varchar(max) = Stuff((Select ',' + QuoteName(format(D,'MMM yyyy'))
From (
Select Top (DateDiff(MONTH,@Date1,@Date2)+1)
D=DateAdd(MONTH,-1+Row_Number() Over (Order By Number),@Date1)
From master..spt_values
) A
For XML Path('')),1,1,'')
Select @SQL = '
Select [YAxis] as [Division],' + @SQL + '
From (
Select YAxis = concat(''Division '',A.DivisionID)
,XAxis = format(D,''MMM yyyy'')
,Value = 1
From #YourTable A
Join (
Select Top (DateDiff(MONTH,'''+concat('',@Date1)+''','''+concat('',@Date2)+''')+1)
D=DateAdd(MONTH,-1+Row_Number() Over (Order By Number),'''+concat('',@Date1)+''')
From master..spt_values
) B
on D between DateFromParts(Year(StartDate),month(StartDate),1) and EOMonth(IsNull(EndDate,GetDate()))
) A
Pivot (sum(Value) For [XAxis] in (' + @SQL + ')) p'
Exec(@SQL);
返回
首先,你需要你想顯示的月份。你可以爲此使用一個值子句。然後加入表格,以便獲得適用於一個月的記錄。然後彙總/每個部門和每月的數據。 (通常,數據透視是在應用程序中完成的,而不是在SQL中完成的:SQL獲取數據,該應用程序關心演示文稿。) –