数据透视表条目

时间:2011-11-25 10:17:42

标签: sql sql-server

我有一张像

这样的表格
R_Id    M_ID      Y_ID  Value
100000  1          1    10
100000  1          2    20
100000  1          3    30    
100001  1          1    10
100001  1          2    20
100001  1          3    30    
100002  1          1    10
100002  1          2    20
100002  1          3    30

我想要一个像

这样的轮回结果
  100000   1   1    10  1    2    20   1   3   30
  100001   1   1    10  1    2    20   1   3   30
  100002   1   1    10  1    2    20   1   3   30

我对旋转有点新意。任何人都可以建议我查询。

基本上我需要的是,对于所有那些重复的R_Id,我需要只显示一行和 在右侧重复行作为列。
注意列数不固定。它可能会改变。

1 个答案:

答案 0 :(得分:0)

如果结果集中的列数是可变的,我将使用动态构建查询。它没有被优化,也许它是脏的方式,但它按你想要的方式工作: - )。

if object_id('tempdb..#t') is not null drop table #t

select * into #t from (
    select 100000 as r_id, 1 as m_id, 1 as y_id, 10 as val union
    select 100000, 1, 2, 20 union select 100000, 1, 3, 30 union 
    select 100001, 1, 1, 10 union select 100001, 1, 2, 20 union 
    select 100002, 1, 1, 10 union select 100002, 1, 2, 20 union 
    select 100002, 1, 3, 30
) t

if object_id('tempdb..#tab') is not null drop table #tab

select r_id, m_id, y_id, val, row_number() over (partition by r_id order by r_id, m_id, y_id) as row_num
into #tab
from #t

declare @qt int, @q nvarchar(max), @i int, @qj nvarchar(max)

select top 1 @qt = count(*) from #tab group by r_id order by count(*) desc

set @q = 'select t.r_id'
set @qj = ' from (select distinct r_id from #tab) t'

set @i = 1
while @i <= @qt
begin
    set @q = @q + ', t' + cast(@i as varchar) + '.m_id, t' + cast(@i as varchar) + '.y_id, t' + cast(@i as varchar) + '.val'
    set @qj = @qj + ' left join #tab t' + cast(@i as varchar) + ' on t' + cast(@i as varchar) + '.r_id = t.r_id and t' + cast(@i as varchar) + '.row_num = '
    if @i = 1 set @qj = @qj + '1'
    else set @qj = @qj + 't'+cast(@i -1 as varchar)+'.row_num + 1'
    set @i = @i + 1
end

set @q = @q + @qj

exec sp_executesql @q
相关问题