我之前发布了一个枢轴问题并得到了回答。但是,这种特殊情况需要日期作为标题,并且每次生成数据透视表时日期都会更改(并且是未知的)。我相信我需要基于一些样本的动态透视/取消透视,但我无法弄清楚语法。
这是表格:
CREATE TABLE [dbo].[PhaseFlowChart](
[pfckey] [int] NULL,
[hourlykey] [bigint] NULL,
[daykey] [bigint] NULL,
[weekkey] [int] NULL,
[monthkey] [int] NULL,
[bbkey] [int] NULL,
[Day] [varchar](100) NULL,
[Date] [varchar](100) NULL,
[Bull Bear Gap] [varchar](100) NULL,
[Monthly] [varchar](100) NULL,
[Weekly] [varchar](100) NULL,
[Daily] [varchar](100) NULL,
[Hour 1] [varchar](100) NULL,
[Hour 2] [varchar](100) NULL,
[Hour 3] [varchar](100) NULL,
[Hour 4] [varchar](100) NULL,
[Hour 5] [varchar](100) NULL,
[Hour 6] [varchar](100) NULL,
[Hour 7] [varchar](100) NULL
) ON [PRIMARY]
我不需要输出中的任何“关键”列。因此这里有一个简单的选择:
select [DAY],[Date],[Bull Bear Gap],[Monthly],[Weekly],[Daily],[Hour 1],[Hour 2],[Hour 3],[Hour 4],[Hour 5],[Hour 6],[Hour 7]
from PhaseFlowChart
order by pfckey asc
这是上面的输出:
我希望输出(动态透视/取消透视?)看起来像这样(同样,每次生成的日期都会不同,这是每天的):
最后,我在网上找到了这个 sql,但是经过几天的语法操作,我无法弄清楚如何移植它来满足我的需求。
CREATE TABLE #yt
([ID] int, [expense] int, [revenue] int, [date] datetime)
;
INSERT INTO #yt
([ID], [expense], [revenue], [date])
VALUES
(1, 43, 45, '2012-12-31 00:00:00'),
(2, 32, 32, '2013-01-01 00:00:00'),
(3, 64, 56, '2013-01-31 00:00:00'),
(4, 31, 32, '2013-03-03 00:00:00')
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(c.col+'_'+convert(varchar(10), #yt.date, 110))
from #yt
cross apply
(
select 'expense' col union all
select 'revenue'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT id,' + @cols + '
from
(
select id,
col+''_''+convert(varchar(10), date, 110) new_col,
value
from #yt
unpivot
(
value
for col in (expense, revenue)
) un
) src
pivot
(
sum(value)
for new_col in (' + @cols + ')
) p '
execute(@query);
非常感谢任何/所有帮助。