我有排一列數從0到3TSQL移調單列爲行
test1
test2
test3
我需要將其轉換成一行列
test1 | test2 | test3
或者
test1
test2
去
test1 | test2 | NULL
我不能使用PIVOT
我不能使用循環
可以將其與單一的查詢做什麼? 硬編碼是可以接受的!
我有排一列數從0到3TSQL移調單列爲行
test1
test2
test3
我需要將其轉換成一行列
test1 | test2 | test3
或者
test1
test2
去
test1 | test2 | NULL
我不能使用PIVOT
我不能使用循環
可以將其與單一的查詢做什麼? 硬編碼是可以接受的!
你的問題是相當模糊,但也許你需要的是這樣的:
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列。
;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
但是否有串各種鏡頭值有可能是行另一份訂單。
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
桌子上有沒有ID?還是別的什麼來分組行? – gofr1