列数未知的简单SQL Pivot查询

时间:2019-06-13 12:53:05

标签: sql pivot

我有以下示例数据:

Item  Location
A   K
A   X
B   W
B   Z
B   Y
C   L

我想要这样的结果:

Item    Loc1    Loc2    Loc3
A       K       X
B       W       Z       Y
C       L

使用SQL Pivot运算符可以吗?

2 个答案:

答案 0 :(得分:0)

我更喜欢条件聚合:

select item,
       max(case when seqnum = 1 then location end) as location_1,
       max(case when seqnum = 2 then location end) as location_2,
       max(case when seqnum = 3 then location end) as location_3
from (select t.*, 
             row_number() over (partition by loc order by loc) as seqnum
      from t
     ) t
group by item;

答案 1 :(得分:0)

这是将透视查询语法与动态sql一起使用以生成所需格式的列的一种方法。

首先,我使用一个表变量来存储列名,这是通过窗口函数生成的,该函数对项目进行分区,然后对位置进行排序,然后将其与“ Loc”组合以生成Loc1,Loc2等。

然后将它们通过管道传递到一个变量中,该变量将构成列列表。这是通过while循环完成的,以按顺序添加每个新列。

从那里,我整理列列表以删除结尾的逗号。

之后,我生成了sql语句,用于在相关点解析列变量。然后执行此操作,生成所需的结果集。

create table #table (
    item char(1),
    location char(1)
);

insert #table (item, location)
values
('A',   'K'),
('A',   'X'),
('B',   'W'),
('B',   'Z'),
('B',   'Y'),
('C',   'L');

declare @pivotcols nvarchar(max)='';
declare @sql nvarchar(max)='';

declare @cols table (
colname nvarchar(150),
rowno int
);


insert @cols
select distinct '[Loc'+cast(rowno as nvarchar(10))+'],', rowno from
(
select row_number()over(partition by item order by location) as rowno,
       item, location 
from #table t)colgenerator;

while exists (select 1 from @cols)
    begin
    select top 1 @pivotcols = @pivotcols+colname from @cols order by rowno;
    delete from @cols where rowno in (select top 1 rowno from @cols order by rowno);
    end


select @pivotcols=substring(@pivotcols, 1, len(@pivotcols)-1);

select @sql=N'select item, '+@pivotcols+'
from (
select rowno, item, location from
(
select ''Loc''+cast(row_number()over(partition by item order by location) as nvarchar(1000)) as rowno,
       item, location 
from #table t)x)src
pivot (max(location) for rowno in ('+@pivotcols+')) piv;';


exec(@sql);

drop table #table;

enter image description here