我有一個非常棘手的問題要問你所有合併含有相同ID但不同的數據轉換成一排兩排
假設我有以下各表
表ACCOUNTTYPE:
Id Type
1 Checking
2 Savings
表Customer_Account:
Customer_Id Account_Type_Id
450 1
450 2
451 1
表Customer_Account包含客戶賬號及其賬戶類型ID列表。 Account_Type_Id是來自AccountType.Id的外鍵。
假設在Customer_Account表,命名爲約什(ID 450)一個客戶可以有既一個檢查和上面示出的儲蓄賬戶作爲。我可以輸出這個客戶與他的ID和像這樣的帳戶類型由具有LEFT JOIN兩次在ACCOUNTTYPE表:
SELECT CustAccount.Customer_Id AS Id, Account1.Type AS Account_Type_1, Account2.Type AS Account_Type_2
FROM Customer_Account CustAccount
LEFT JOIN AccountType Account1
ON Account1.Id = CustAccount.Account_Type_Id
LEFT JOIN AccountType Account2
ON Account2.Id = CustAccount.Account_Type_Id
輸出將是:
Id Account_Type_1 Account_Type_2
450 Checking Checking
450 Savings Savings
451 Checking Checking
我是什麼試圖做的是,如果像Josh(id 450)這樣的客戶有這兩個一個檢查和一個儲蓄帳戶,我想輸出上面的兩行數據成一行像這樣:
Id Account_Type_1 Account_Type_2
450 Checking Savings
還有,如果客戶只有一個類型的帳戶(如客戶ID爲451這裏),我只希望這種類型的賬號對應的列下出現像這樣:
Id Account_Type_1 Account_Type_2
451 Checking
或者,如果客戶ID爲451只有一個儲蓄賬戶的輸出中應該是:
Id Account_Type_1 Account_Type_2
451 Savings
我想「檢查」只Accoun_Type_1和「儲蓄」下出現Account_Type_2下。如果我做一個GROUP BY CustAccount.Customer_Id,我得到這個:
Id Account_Type_1 Account_Type_2
450 Checking Checking
451 Checking Checking
任何專家的任何幫助將是非常讚賞。
謝謝。
我不明白你的表是什麼樣的。表'Customers'有一個'Account_Id'字段和'Customer_Id'字段?而'Josh'在這張表中出現了兩次,兩個都有相同的Customer_Id? –
表客戶有列Id,Name,Account_Type_1,Account_Type_2和Account_Type_Id(來自表AccountType的外鍵) – user765368
我很確定你在這裏感到困惑。 Account_Type_1是您在查詢的結果集中引入的名稱,它似乎不是您的Customers表中的列。 –