SQL 服务器中带有日期的 Pivot 和 UnPivot 功能
Pivot & UnPivot functionality with dates in SQL Server
我目前正在使用 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
Sample table, with expected result
好吧,根据您的示例数据,一个区域的前 6 个对于每个区域都是相同的,因为区域是列名称。有了这些信息,我们可以在原始枢轴之后使用动态反枢轴。
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
我目前正在使用 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
Sample table, with expected result
好吧,根据您的示例数据,一个区域的前 6 个对于每个区域都是相同的,因为区域是列名称。有了这些信息,我们可以在原始枢轴之后使用动态反枢轴。
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