我有一个非常棘手的问题
假设我有以下表格
表帐户类型:
Id Type
1 Checking
2 Savings
表 Customer_Account :
Customer_Id Account_Type_Id
450 1
450 2
451 1
表 Customer_Account 包含客户ID及其帐户类型ID的列表。 Account_Type_Id是来自AccountType.Id。
的外键假设在 Customer_Account 表中,名为Josh(id 450)的客户可以拥有两者支票和储蓄帐户,如上所示。我可以通过在 AccountType 表上两次LEFT JOIN来输出此客户的ID和帐户类型:
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下的“Savings”下。如果我执行GROUP BY CustAccount.Customer_Id,我会得到:
Id Account_Type_1 Account_Type_2
450 Checking Checking
451 Checking Checking
非常感谢任何专家的帮助。
感谢。
答案 0 :(得分:2)
这看起来像是一个完整的外部联接的直接应用程序:
SELECT COALESCE(ac1.id, ac2.id) AS id, ac1.Account_Type_1, ac2.Account_Type_2
FROM (SELECT c.Customer_ID AS Id, t.Type AS Account_Type_1
FROM Customer_Account AS c
JOIN AccountType AS t ON c.Account_Type_ID = t.ID AND t.ID = 1) AS ac1
FULL OUTER JOIN
(SELECT c.Customer_ID AS Id, t.Type AS Account_Type_2
FROM Customer_Account AS c
JOIN AccountType AS t ON c.Account_Type_ID = t.ID AND t.ID = 2) AS ac2
ON ac1.Id = ac2.Id;
如果您的DBMS不支持FULL OUTER JOIN但支持LEFT OUTER JOIN,那么您可以使用:
SELECT ac0.id, ac1.Account_Type_1, ac2.Account_Type_2
FROM (SELECT DISTINCT c.Customer_ID AS Id FROM Customer_Account AS c) AS ac0
LEFT OUTER JOIN
(SELECT c.Customer_ID AS Id, t.Type AS Account_Type_1
FROM Customer_Account AS c
JOIN AccountType AS t ON c.Account_Type_ID = t.ID AND t.ID = 1) AS ac1
ON ac0.id = ac1.id
LEFT OUTER JOIN
(SELECT c.Customer_ID AS Id, t.Type AS Account_Type_2
FROM Customer_Account AS c
JOIN AccountType AS t ON c.Account_Type_ID = t.ID AND t.ID = 2) AS ac2
ON ac0.Id = ac2.Id;
第一个子查询生成存在的客户ID列表;第二个生成帐户类型1的列表(检查);第三个生成帐户类型2的列表(保存)。联接确保每个帐户都得到正确识别。
答案 1 :(得分:1)
答案 2 :(得分:1)
为ON子句添加更多条件:
ON Account1.Id = CustAccount.Account_Type_Id and Account1.Account_Type_Id = 1
ON Account2.Id = CustAccount.Account_Type_Id and Account2.Account_Type_Id = 2
将导致输出包括客户持有的帐户。如果他们只有一个帐户,那么另一个帐户类型将为NULL。
编辑:对不起,我没有意识到你没有客户表。您可以创建一个包含不同Customer_Id值列表的临时表,并将其用作JOIN中的第一个表。
select distinct Customer_Id into #Customers
from Customer_Account
或者说得更直接:
select distinct C.Customer_Id,
( select 'Checking' from Customer_Account where Customer_Id = C.CustomerId and Account_type_Id = 1 ) as Account_Type_1,
( select 'Savings' from Customer_Account where Customer_Id = C.CustomerId and Account_type_Id = 2 ) as Account_Type_2,
from Customer_Account as C