2016-09-20 63 views
0

我正在編寫一個查詢來計算一段時間內的幾件事的總計。時間增量以每週桶形式存在(每個星期一),但隨着時間的推移,過去不需要任何東西。這意味着我的每週水桶將會漂浮並始終留在將來。我已經看到了一些關於如何設置PIVOT函數的鏈接,但所有這些示例的列都是固定值。如何讓我的查詢結果顯示爲我的列名?如何從動態查詢結果中設置列

這是我的代碼,它輸出我需要我的列名稱。我將增量設置爲「1」以獲得僅4個測試結果,但可能會打開它達12個月。

DECLARE @Startdate as date 
DECLARE @Enddate as date 

SET @Startdate = getdate() 
SET @Enddate = DATEADD(Month,1,@StartDate) 

;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 CONVERT(date,myDate) AS BuildWeek 
FROM cte 
OPTION (MAXRECURSION 0) 
+0

你會想一個動態的支點,這是使用動態SQL樞軸執行。這裏有很多帖子。這是我最近爲某人做的一個。 http://scackoverflow.com/a/39513013/6167855 – scsimon

+0

@scsimon謝謝。我會做更多的閱讀。只需要正確的關鍵字搜索麪包屑。 – Nicho247

+0

沒有汗水。這是一個很酷的教程/解釋。 http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/ – scsimon

回答

0

你將不得不變得充滿活力。

您錯過了一些重要細節。所以我希望這將有助於一些指導。

下面是今天早些時候答案的修改版本。

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 
+0

嗨,約翰 - 謝謝。我想我可以從這裏弄明白,或者至少取得很大進展。 – Nicho247

+0

@ Nicho247毫無疑問,你可以爲你做這項工作。 –