2016-05-14 174 views
1

我有排一列数从0到3TSQL移调单列为行

test1 
test2 
test3 

我需要将其转换成一行列

test1 | test2 | test3 

或者

test1 
test2 

test1 | test2 | NULL 

不能使用PIVOT

不能使用循环

可以将其与单一的查询做什么? 硬编码是可以接受的!

+0

桌子上有没有ID?还是别的什么来分组行? – gofr1

回答

1

你的问题是相当模糊,但也许你需要的是这样的:

select 
    max(case when RN = 1 then value end), 
    max(case when RN = 2 then value end), 
    max(case when RN = 3 then value end) 
from 
(
    select value, row_number() over (order by value) as RN 
    from yourtable 
) x 

这将需要最多列名为值,以便随后的3个值按字母顺序分为3列。

0
;WITH example AS (
SELECT * 
FROM (VALUES 
(1, 'test1'), 
(1, 'test2'), 
(1, 'test3'), 
(2, 'test1'), 
(2, 'test2') 
) as t(id, string) 
) 

SELECT top 1 with ties e1.string, 
         e2.string, 
         e3.string 
FROM example e1 
left join example e2 
    on e1.id = e2.id and e1.string != e2.string 
left join example e3 
    on e1.id = e3.id and e1.string != e3.string and e2.string != e3.string 
ORDER BY ROW_NUMBER() OVER (PARTITION BY e1.id ORDER By e1.string,e2.string,e3.string) 

输出:

string string string 
test1 test2 test3 
test1 test2 NULL 

但是否有串各种镜头值有可能是行另一份订单。

0
create table #t (mycolumn varchar(10)) 

insert into #t values ('test1'),('test2'),('test3'),(NULL) 
declare @r varchar(max) 

select @r = COALESCE(@r + ' | ', '') + COALESCE(mycolumn,'NULL') 
from #t 

select @r 

    input: 
    mycolumn 
    -------- 
    test1 
    test2 
    test3 
    NULL 

    output: 
    test1 | test2 | test3 | NULL