2013-05-13 43 views
0

我看起來像這樣的兩個表:問題與多行合併成單排

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 
+1

請問您能提供一些示例數據行和預期輸出嗎? – gordatron 2013-05-13 15:59:45

+0

向我們提供您正在使用的查詢的SQL,我們將幫助您改進它。另外,你使用的是什麼數據庫?一些對這類事情有用的分組選項是特定於數據庫的。 – 2013-05-13 15:59:47

+0

以什麼方式組合它們? – 2013-05-13 15:59:47

回答

2

可以使用聚合函數與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; 

SQL Fiddle with Demo

或者你可以用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'; 

SQL Fiddle with Demo

+0

我的情況是不使用MAX()參數。這固定了一切!謝謝 :) – 2013-05-13 16:17:09