有如下一張表t0311
希望得到如下結果:
即對相同的no進行轉置
create
table t0311(
noint
,name nvarchar(20)
,age int
)insert
into t0311
select1,
'張三'
,'18'
union
allselect1,
'李四'
,'17'
union
allselect1,
'王五'
,'23'
union
allselect1,
'趙六'
,'40'
union
allselect2,
'tom'
,'17'
union
allselect3,
'bob'
,'19'
union
allselect3,
'tony'
,'36'
union
allselect3,
'petter'
,'25'
官方答案:
;
with
tempas(
select[no
],[name]
,[age]
, row_number(
)over
(partitionby[
no]order
byno
asc)
as"分組排序"
from
[dbo]
.[t0311]
)select[no
],max(
case 分組排序 when
1then
[name]
else
null
end)
as name1,
max(
case 分組排序 when
1then
[age]
else
null
end)
as age1,
max(
case 分組排序 when
2then
[name]
else
null
end)
as name2,
max(
case 分組排序 when
2then
[age]
else
null
end)
as age2,
max(
case 分組排序 when
3then
[name]
else
null
end)
as name3,
max(
case 分組排序 when
3then
[age]
else
null
end)
as age3,
max(
case 分組排序 when
4then
[name]
else
null
end)
as name4,
max(
case 分組排序 when
4then
[age]
else
null
end)
as age4
from
temp
groupby[
no]
變通一下:
begin
declare
@maxcol
int,
@iint=1
,@sql
varchar
(1000)=
''select
@maxcol
=max
(總數)
from
(select
count(1
)as"總數"
from
[dbo]
.[t0311]
groupby[
no]) twhile
@i<=
@maxcol
begin
set@sql
=@sql
+'max(case 分組排序 when '
+cast(
@ias
varchar(1
))+' then [name] else null end) as name'
+cast(
@ias
varchar(1
))+',max(case 分組排序 when '
+cast(
@ias
varchar(1
))+' then [age] else null end) as age'
+cast(
@ias
varchar(1
))+','
set@i+=
1end
-- 消除最後','
iflen
(@sql
)>
0set
@sql
=left
(@sql
,len
(@sql)-
1)-- 組裝最後的sql查詢
set@sql
=';with temp as (select [no],[name],[age],row_number() over(partition by [no] order by no asc) as "分組排序" from [dbo].[t0311]) select [no],'
+@sql
+' from temp group by [no]'
exec
(@sql
)end
因為官方寫的是固定列考點:
row_number() over(partition by 列 order by 列)
參考:sql每日一題(20210311) SQL每日一題 20210318
create table t0318 id int redate date temp int insert into t0318 values 1 2020 1 1 10 insert into t0318 values 2 2020 1 2 18 insert into t0318 values ...
每日一題 1
題目詳情 peter喜歡玩數字遊戲,但數獨這樣的遊戲對他來說太簡單了,於是他準備玩乙個難的遊戲。遊戲規則是在乙個n n的 裡填數,規則 對於每個輸入的n,從左上角開始,總是以對角線為起點,先橫著填,再豎著填。這裡給了一些樣例,請在樣例中找到規律並把這個n n的 列印出來吧。輸入描述 多組測試資料 資...
每日一題2018 3 21
leetcode 2 模擬十進位制運算考察單鏈表基本操作。題無難點,個人基礎需要提高。definition for singly linked list.struct listnode class solution while p while q if shi val s next null ret...