我遇到了一个包含五个字段的表,引用了一个客户列表。字段(c1,c2等)是另一个表中客户的id。需要一个SQL语句,将客户名称解析为一个在线报告和五个entires。例如:
Table1
ID Description C1 C2 C3
1 PartyGroup 2 3 1
2 BeerFolk 1 0 2
Customer table
ID Name
1 Rob
2 Joe
3 Fred
Output:
ID Description Cust1 Cust2 Cust3
1 PartyGroup Joe Fred Rob
2 BeerFolk Rob Joe
任何想法都会受到赞赏......
答案 0 :(得分:2)
SELECT t1.ID, t1.Description, c1.Name AS Cust1, c2.Name AS Cust2, c3.Name AS Cust3
FROM Table1 t1
LEFT JOIN Customer c1
ON t1.C1 = c1.ID
LEFT JOIN Customer c2
ON t1.C2 = c2.ID
LEFT JOIN Customer c3
ON t1.C3 = c3.ID
答案 1 :(得分:0)
你需要在from子句中多次引用customer表 - 将它们别名为c1,c2,c3等 - 然后正常链接。
与此类似:
select t.id, t.description, c1.name "Cust1", c2.name "Cust2", c3.name "Cuat3"
from table1 t, customer c1, customer c2, customer c3
where t.c1 = c1.id
and t.c2 = c2.id
and t.c3 = c3.id
答案 2 :(得分:0)
另一种方法是使用UNION或UNION ALL:
来规范化表TRANSFORM First(Customer.Name) AS FirstOfName
SELECT Norm.ID, Norm.Description
FROM Customer
INNER JOIN (
SELECT ID, Description, "C1" As Cust, C1 As CID
FROM table1
UNION
SELECT ID, Description, "C2" As Cust, C2 As CID
FROM table1
UNION
SELECT ID, Description, "C3" As Cust, C3 As CID
FROM table1) AS Norm
ON Customer.ID = Norm.CID
GROUP BY Norm.ID, Norm.Description
PIVOT Norm.Cust