sql行到列。 sql 2008R2

时间:2018-01-25 17:16:45

标签: sql sql-server tsql

create table temptest 
(lid varchar(10), dat varchar(20))

insert into temptest (lid,dat) values ('11','first')
insert into temptest (lid,dat) values ('11','second')
insert into temptest (lid,dat) values ('11','third')

insert into temptest (lid,dat) values ('12','box')
insert into temptest (lid,dat) values ('12','circle')
insert into temptest (lid,dat) values ('12','trap')

insert into temptest (lid,dat) values ('14','star')
insert into temptest (lid,dat) values ('14','planet')

我希望结果为:

lid, dat1, dat2, dat3
11,first,second,third
12, box, circle, trap
14, star, planet, <blank>

2 个答案:

答案 0 :(得分:1)

试试这个:

;with sourceTable as
(
  Select lid, 
         dat, 
         case RN 
                 when 1 then 'dat1' 
                 when 2 then 'dat2' 
                 when 3 then 'dat3' 
         end as dat#
  from(
    select *, ROW_NUMBER() over (partition by lid order by lid ) as RN from temptest
    )as K
) 
Select lid,[dat1],[dat2],[dat3] from sourceTable
pivot
(
   MIN(dat) for dat# in ([dat1],[dat2],[dat3])
)as P

答案 1 :(得分:0)

在SQL服务器中心也回答了这个问题:

` ;
WITH CTE AS
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY lid ORDER BY dat) AS rn
    FROM #temptest
)

SELECT lid,
MAX(CASE WHEN rn = 1 THEN dat END) AS dat1,
MAX(CASE WHEN rn = 2 THEN dat END) AS dat2,
MAX(CASE WHEN rn = 3 THEN dat END) AS dat3
FROM CTE
GROUP BY lid`