3

有没有办法将动态数据透视查询的结果直接存储到固定表中?由于结果是动态的,我无法通过指定列名和方法来创建表,例如“create table MyTable as (pivot select statement)”似乎在 SQL Server 上失败(“关键字'AS'附近的语法不正确”)。我试图格式化下面的 SQL 以获得 SELECT - INTO - FROM 结构,但没有这样做。任何帮助显然都非常感谢!

用于枢轴的 SQL 是(感谢这个伟大的网站!):

declare @pivot varchar(max), @sql varchar(max)
create table pivot_columns (pivot_column varchar(100))

insert into pivot_columns
select distinct DateField from MyTable order by 1

select @pivot=coalesce(@pivot+',','')+'['+pivot_column+']'from pivot_columns

set @sql = 'SELECT * FROM (select DateField, RefCode, SumField from MyTable) p
PIVOT
(sum(SumField) FOR DateField IN  ( ' + @pivot + ') ) 
AS pvl'

drop table pivot_columns

exec (@sql)
4

1 回答 1

2

除非我没有遵循您要执行的操作,否则您应该能够INTO mynewTable将要执行的 sql 添加到您的 sql 中,并且您应该获得新表。

declare @pivot varchar(max), @sql varchar(max)
create table pivot_columns (pivot_column varchar(100))

insert into pivot_columns
select distinct DateField from MyTable order by 1

select @pivot=coalesce(@pivot+',','')+'['+pivot_column+']'from pivot_columns

set @sql = 'SELECT * INTO mynewTable FROM (select DateField, RefCode, SumField from MyTable) p
PIVOT
(sum(SumField) FOR DateField IN  ( ' + @pivot + ') ) 
AS pvl'

drop table pivot_columns

exec (@sql)

我只是测试在以下脚本中创建一个新表,它为我提供了一个在数据库中使用的新表:

create table t
( 
    [month] int, 
    [id] nvarchar(20), 
    [cnt] int 
)

insert t values (4,'TOTAL',214)
insert t values (5,'TOTAL',23)
insert t values (6,'TOTAL',23)
insert t values (4,'FUNC',47)
insert t values (5,'FUNC',5)
insert t values (6,'FUNC',5)
insert t values (4,'INDIL',167)
insert t values (5,'INDIL',18)
insert t values (6,'INDIL',18)


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(month) 
            FROM t 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT *
            INTO tabletest from 
            (
                select month, id, cnt
                from t
           ) x
            pivot 
            (
                 sum(cnt)
                for month in (' + @cols + ')
            ) p '


execute(@query)

drop table t
于 2012-06-06T14:35:47.650 回答