簡體   English   中英

從 2 列表(行到列)創建具有多列的表

[英]Create table with multiple columns from a 2 columns table (rows to columns)

我有以下問題需要您的幫助才能使用 Resource 表中的數據創建 Result 表

我有一個“資源”表:

代碼 價值
一個 100
100
C 220
一個 150
C 300
D 120
120

使用 SQL 創建“結果”表:

代碼1 價值1 代碼2 價值2 代碼3 價值3
一個 100 100 C 220
一個 150 C 300 D 120
120

我的想法是創建 3 個表然后加入它們,但我不知道如何獲得第一、第二和第三行。 有沒有人有更優化的方法?

感謝您閱讀我的問題!

模式和插入語句:

 create table Resource (Code varchar(10),   Value int);

 insert into Resource values('A',   100);
 insert into Resource values('B',   100);
 insert into Resource values('C',   220);
 insert into Resource values('A',   150);
 insert into Resource values('C',   300);
 insert into Resource values('D',   120);
 insert into Resource values('E',   120);

查詢#1:

 with cte as 
 (
 select *,row_number()over(order by null) rn from Resource
 )
 select (case when rn%3=1 then code end) as Code1, (case when rn%3=1 then value end) as Value1
 ,(case when rn%3=2 then code end) as Code2, (case when rn%3=2 then value end) as Value2,
 (case when rn%3=0 then code end) as Code3, (case when rn%3=0 then value end) as Value3
  from cte 

Output:

代碼1 價值1 代碼2 價值2 代碼3 價值3
一個 100 null null null null
null null 100 null null
null null null null C 220
一個 150 null null null null
null null C 300 null null
null null null null D 120
120 null null null null

查詢#2

 with cte as 
 (
 select *,row_number()over(order by null) rn from Resource
 )
 ,Code1 as 
  ( 
  select Code Code1, value  Value1
  , row_number()over(order by null) rownumber
  from cte n where rn%3=1
  )
 ,Code2 as
  ( 
  select Code Code2, value  Value2
  , row_number()over(order by null) rownumber
  from cte n where rn%3=2 
  )
 ,Code3 as
  ( 
  select Code Code3, value  Value3
  , row_number()over(order by null) rownumber
  
  from cte n where rn%3=0
  )
  
  select *,code1.rownumber from Code1 left join Code2 on Code1.rownumber=Code2.rownumber
  left join Code3 on Code2.rownumber = Code3.rownumber
  
  
  
代碼1 價值1 行號 代碼2 價值2 行號 代碼3 價值3 行號 行號
一個 100 1 100 1 C 220 1 1
一個 150 2 C 300 2 D 120 2 2
120 3 null null null null null null 3

db<小提琴在這里

您沒有為行指定任何排序,因此我按(code, value)對它們進行了排序。 請記住,表中的行沒有任何固有的順序(例如,在電子表格中)。

你可以做:

with
x as (
  select *,
    (row_number() over(order by code, value) - 1) / 3 as line,
    (row_number() over(order by code, value) - 1) % 3 as col
  from t
)
select
  a.code as code1, a.value as value1,
  b.code as code2, b.value as value2,
  c.code as code3, c.value as value3
from x a
left join x b on b.line = a.line and b.col = 1
left join x c on c.line = a.line and c.col = 2
where a.col = 0;

結果:

 code1  value1  code2  value2  code3  value3 
 ------ ------- ------ ------- ------ ------ 
 A      100     A      150     B      100    
 C      220     C      300     D      120    
 E      120     null   null    null   null   

請參閱DB Fiddle上的運行示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM