[英]Issue with multiple rows combining into single row
我有兩個看起來像這樣的表:
Table_X
id, cert_number, other random info
Table_Y
id, cert_number, type, name
出現這個問題是因為我在表y中有不同的類型,它們都適用於我想要返回的單個結果(即:所有者名稱,運營商名稱,目的地名稱),這些結果基於該類型。
有沒有辦法可以將這些結果與owner_name,carrier_name和destination_name合並為一個結果?
我使用CASE正確地將信息輸入到結果中,但由於我在select語句中使用了type字段,因此每個cert_number返回3個結果。
提前致謝!
編輯:
這是一些示例數據。 由於我需要傳遞大量參數並檢查,因此實際的SQL語句非常長。
table_x
id | cert_number
1 123-XYZ
2 124-zyx
table_y
id | cert_number | type | name
1 123-XYZ owner bob
2 123-XYZ destination paul
3 124-zyx owner steve
4 123-xyz carrier george
5 124-zyx carrier mike
6 124-zyx destination dan
您可以將聚合函數與CASE
表達式一起使用:
select x.cert_number,
max(case when y.[type] = 'owner' then y.name end) owner_name,
max(case when y.[type] = 'carrier' then y.name end) carrier_name,
max(case when y.[type] = 'destination' then y.name end) destination_name
from table_x x
inner join table_y y
on x.cert_number = y.cert_number
group by x.cert_number;
或者您可以多次加入您的桌面type
:
select x.cert_number,
y1.name as owner_name,
y2.name as carrier_name,
y3.name as destination_name
from table_x x
left join table_y y1
on x.cert_number = y1.cert_number
and y1.type = 'owner'
left join table_y y2
on x.cert_number = y2.cert_number
and y2.type = 'carrier'
left join table_y y3
on x.cert_number = y3.cert_number
and y3.type = 'destination';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.