簡體   English   中英

聯接數據-行到列?

[英]JOIN DATA - ROWS TO COLUMNS?

我是菜鳥,請幫幫我。

表格1

id, options1, options2, options3
-----------------------------------------
1, 'a', 'b', 'c'
2, 'x', 'b', 'c'
3, 'c', 'b', 'd'
4, 'z', 'b', 'c'

表2

id, productid, name
-------------------
1, 1, "Title"
2, 1, "Color"
3, 2, "Title"
4, 3, "Title"
5, 4, "Title"
6, 4, "Color"
7, 4, "Size"

// product_id的行數不同(最小值= 0和最大值= 3)

如何獲得:table3

productid, new_name
--------------------
1, "Title a; Color b; c"
2, "Title x; b; c"
3, "Title c; b, d"
4, "Title z; Color b; Size c" 

好的,我想發表評論,但我沒有信譽點,但我想為您提供幫助。

您的架構有點錯誤。 這些表應該可以通過ID或productID進行聯接。 如果運行以下查詢,您將注意到這些查詢未產生您想要的結果,並且無法將table1中的選項附加到table2中的產品:

select table2.productid, * from table1 
full outer join table2 on table1.id = table2.id

要么

select table2.productid, * from table1 
full outer join table2 on table1.id = table2.productid

您可以糾正表2:

table2
productid
id
value1 as nullable
value2 as nullable
value3 as nullable

由於我的數據庫中沒有這些表,因此我即時修改了該表:

select 1 as id , 1 as productid , 'Title' as value1,'Color' as value2, null as value3  union
select 2 as id , 2 as productid , 'Title' as value1, null , null  union
select 3 as id , 3 as productid , 'Title' as value1, null , null  union
select 4 as id , 4 as productid , 'Title' as value1, 'Color' as value2, 'Size' as value3

這樣,您的選項將與它們的值匹配:

select 
    value1, options1,
    value2, options2,
    value3, options3
  from table1 join table2 on table1.id=table2.id

這可以進一步完善為

select 
    productid,
    coalesce(value1,'') +' '+ coalesce(options1,'') + '; ' +
    coalesce(value2,'')+' '+ coalesce(options2,'') +'; '+
    coalesce(value3,'')+' '+ coalesce(options3,'') as new_name
     from  #tb3 join #tb1 on #tb3.id=#tb1.id

這將產生您需要的結果:

productid   new_name
----------- ------------------------
1           Title a; Color b;  c
2           Title x;  b;  c
3           Title c;  b;  d
4           Title z; Color b; Size c

但是,更好的方法是用另一個選項創建另一個表,並且在該表中可以有一個或多個選項(超過3個)

如果適合您,請標記答案。 謝謝

暫無
暫無

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

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