也许,最简单和最直接的方法是将所有明细表左连接到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
;