也許,這樣做的最簡單,最直接的方法是將左加入所有細節表到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