也许,这样做的最简单,最直接的方法是将左加入所有细节表到Product
表,然后筛选出具有没有匹配的所有产品。
所以,这将基本上@ Santhosh的一个小调整溶液(强调):
SELECT
pr.Ref,
pr.Description,
st.Current_Stock,
sa.Qty_Sold,
po.Qty_Outstanding
FROM Product pr
LEFT JOIN Stock st ON st.Ref = pr.Ref
LEFT JOIN Sales sa ON sa.Ref = pr.Ref
LEFT JOIN POs po ON po.Ref = pr.Ref
WHERE st.Ref IS NOT NULL OR sa.Ref IS NOT NULL OR so.Ref IS NOT NULL
;
还有一个不那么明显的替代:工会的所有详细信息表,然后转动详细数据。结果集仅包含对至少包含一些详细信息的产品的引用。因此,您可以将结果集内部加入Product
以访问输出的产品说明。
如果你的SQL产品支持PIVOT子句中,你可以做这样的:
SELECT
p.Ref,
p.Description,
s.Current_Stock,
s.Qty_Sold,
s.Qty_Outstanding
FROM (
SELECT
Ref,
Current_Stock,
Qty_Sold,
Qty_Outstanding
FROM (
SELECT
Ref,
'Current_Stock' AS Attribute,
Current_Stock AS Value
FROM Stock
UNION ALL
SELECT
Ref,
'Qty_Sold',
Qty_Sold
FROM Sales
UNION ALL
SELECT
Ref,
'Qty_Outstanding',
Qty_Outstanding
FROM POs
) d
PIVOT (
SUM(Value) FOR Attribute IN (
Current_Stock,
Qty_Sold,
Qty_Outstanding
)
) p
) s
INNER JOIN Product p ON p.Ref = s.Ref
;
还有回转的老年人和更普遍的方法,为此,你需要使用分组和有条件聚集:
SELECT
p.Ref,
p.Description,
SUM(CASE Attribute WHEN 'Current_Stock' THEN d.Value END) AS Current_Stock,
SUM(CASE Attribute WHEN 'Qty_Sold' THEN d.Value END) AS Qty_Sold,
SUM(CASE Attribute WHEN 'Qty_Outstanding' THEN d.Value END) AS Qty_Outstanding
FROM (
SELECT
Ref,
'Current_Stock' AS Attribute,
Current_Stock AS Value
FROM Stock
UNION ALL
SELECT
Ref,
'Qty_Sold',
Qty_Sold
FROM Sales
UNION ALL
SELECT
Ref,
'Qty_Outstanding',
Qty_Outstanding
FROM POs
) d
INNER JOIN Product p ON p.Ref = d.Ref
GROUP BY
p.Ref,
p.Description
;
您使用的是什么RDBMS。是否在所有4个表中都提供了唯一的产品ID? – 2013-04-05 11:26:19