你將不得不變得充滿活力。
您錯過了一些重要細節。所以我希望這將有助於一些指導。
下面是今天早些時候答案的修改版本。
Declare @Startdate as date,@Enddate as date
Set @Startdate = getdate()
Set @Enddate = DATEADD(Month,1,@StartDate)
Declare @SQL varchar(max) = ''
Declare @Col varchar(max) = '
,[Title] = sum(case when Date between ''[DateR1]'' and ''[DateR2]'' then [YourField] else null end)'
;with cte(myDate) as (
Select Case When DatePart(Day,@StartDate) = 1 Then @StartDate Else DateAdd(Week,DateDiff(Week,0,@StartDate)+1,0) end as myDate
Union All
Select DateAdd(Week,1,myDate)
From cte
Where DateAdd(Week,1,myDate) <= @EndDate
)
Select @SQL = @SQL + Replace(Replace(Replace(@Col,'[DateR1]',DateR1),'[DateR2]',DateR2),'Title',Title)
From (Select DateR1 = cast(myDate as Date)
,DateR2 = DateAdd(DAY,6,cast(myDate as Date))
,Title = 'Week Of '+Substring(DateName(WEEKDAY,myDate),1,3)+' '+Substring(DateName(MONTH,myDate),1,3)+' '+cast(Day(myDate) as varchar(5))
From cte
) A
Set @SQL = 'Select ID'[email protected]+'
From YourTable
Group By ID
'
Print @SQL
--Exec(@SQL)
返回下面的SQL這將
Select ID
,[Week Of Mon Sep 26] = sum(case when Date between '2016-09-26' and '2016-10-02' then [YourField] else null end)
,[Week Of Mon Oct 3] = sum(case when Date between '2016-10-03' and '2016-10-09' then [YourField] else null end)
,[Week Of Mon Oct 10] = sum(case when Date between '2016-10-10' and '2016-10-16' then [YourField] else null end)
,[Week Of Mon Oct 17] = sum(case when Date between '2016-10-17' and '2016-10-23' then [YourField] else null end)
From YourTable
Group By ID
你會想一個動態的支點,這是使用動態SQL樞軸執行。這裏有很多帖子。這是我最近爲某人做的一個。 http://scackoverflow.com/a/39513013/6167855 – scsimon
@scsimon謝謝。我會做更多的閱讀。只需要正確的關鍵字搜索麪包屑。 – Nicho247
沒有汗水。這是一個很酷的教程/解釋。 http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/ – scsimon