我有一个数据表,如下所示:
DATE Price ---------- ------ 31/12/2009 10 31/12/2009 11 31/12/2009 12 30/12/2009 20 30/12/2009 21 30/12/2009 22 29/12/2009 30 29/12/2009 32 29/12/2009 31
我想转换这些数据,如下所示:
31/12/2009 30/12/2009 29/12/2009 ---------- ---------- ---------- 10 10 10 11 11 11 12 12 12
但是日期列中的值是动态的.所以,我不知道如何使用sql Server Pivot.
能告诉我如何获取这些数据吗?
下面给出了复制此场景的脚本:
CREATE TABLE TEMP(EffectiveDate DATETIME,Price INT) INSERT INTO TEMP(EffectiveDate,Price) SELECT GETDATE(),10 UNION ALL SELECT GETDATE(),11 UNION ALL SELECT GETDATE(),12 UNION ALL SELECT GETDATE()-1,20 UNION ALL SELECT GETDATE()-1,21 UNION ALL SELECT GETDATE()-1,22 UNION ALL SELECT GETDATE()-2,30 UNION ALL SELECT GETDATE()-2,32 UNION ALL SELECT GETDATE()-2,31 SELECT CONVERT(VARCHAR,EffectiveDATE,103) AS 'DATE',Price FROM Temp
提前致谢,
马赫什
解决方法
好吧,正如我所提到的,你的数据没有意义,但也许这可能会有所帮助.
此外,PIVOT要求您使用聚合函数(SUM,AVG,COUNT).
好的,看看这是否可以帮到你.
CREATE TABLE #TEMP (EffectiveDate DATETIME,Price INT) INSERT INTO #TEMP(EffectiveDate,Price) SELECT GETDATE(),10 UNION ALL SELECT GETDATE(),11 UNION ALL SELECT GETDATE(),12 UNION ALL SELECT GETDATE()-1,20 UNION ALL SELECT GETDATE()-1,21 UNION ALL SELECT GETDATE()-1,22 UNION ALL SELECT GETDATE()-2,30 UNION ALL SELECT GETDATE()-2,32 UNION ALL SELECT GETDATE()-2,31 DECLARE @Cols VARCHAR(MAX) SELECT @cols = COALESCE(@cols + ',[' + colName + ']','[' + colName + ']') FROM ( SELECT DISTINCT CONVERT(VARCHAR,103) colName FROM #TEMP ) s ORDER BY colName DESC DECLARE @query VARCHAR(MAX) SET @query = N'SELECT * FROM (SELECT CONVERT(VARCHAR,103) AS ''DATE'',Price FROM #TEMP) p PIVOT ( SUM(Price) FOR DATE IN ( '+ @cols +' ) ) AS pvt' EXECUTE(@query) DROP TABLE #TEMP