我目前正在使用pivot,unpivot检索最后6个可用日期数据。任何人都可以帮我解决这个问题吗?
select *
from #myTable
unpivot (value for Area in (abc,def,fgh,ijk,klp)) up
pivot (max(value) for [date] in (
##-- Here I need to get the last 6 available dates less than current date
)) p
[Date]
列的数据类型为DATE.
我的数据库中的日期示例值
2017-09-16,
2017-09-09,
2017-09-02,
2017-08-26,
2017-07-22,
2017-07-01,
2017-06-24,
2017-06-11
答案 0 :(得分:0)
那么,根据您的样本数据,每个区域的一个区域的前6个是相同的,因为Area是列名称。有了这些信息,我们可以在原始数据透视后使用动态unpivot。
declare @table table (TheDate date, abc int, def int, fgh int, ijk int, klp int)
insert into @table
values
('20170916',1,2,34,4,5),
('20170909',2,3,4,5,676),
('20170902',6,7,8,8,9)
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
if object_id('tempdb..#staging') is not null drop table #staging
select
Area
,TheDate
,Val
into #staging
from @table
unpivot
(Val for Area in (abc,def,fgh,ijk,klp)
) up
--Get distinct values of the PIVOT Column / top 6 by date
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(TheDate)
FROM (SELECT DISTINCT TOP 6 TheDate FROM #staging ORDER BY TheDate DESC) AS TheDate
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT Area, ' + @ColumnName + '
FROM #staging
PIVOT(SUM(Val)
FOR TheDate IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
<强> See It In Action Here 强>