SQL;完全左,右,上,内,后连接

时间:2013-04-05 11:21:24

标签: sql join

似乎无法理解这一点。我有三个表(库存,销售,采购订单)与产品有关,有一个共同的领域,可以将它们全部加入。我有第四张表,里面有所有产品。产品可能有也可能没有这些表格中的信息(库存,销售,采购订单),但在产品表中会有记录。

我需要每个产品最多一行,其中包含三个表格中的信息(库存,销售和采购订单)。

表格的简化视图如下:

产品表,参考,说明

股票表,Ref,Current_Stock

销售表,Ref,Qty_Sold

PO表,Ref,Qty_Outstanding

我需要以下结尾:

Ref,Description,Current_Stock,Qty_Sold,Qty_Outstanding

由于

尼格

3 个答案:

答案 0 :(得分:1)

或许,最简单,最直接的方法是将所有详细信息表左连接到Product表,然后筛选出 no 匹配的产品所有

所以,这本质上是@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
;

答案 1 :(得分:0)

SELECT P.REF, P.DESCRIPTION, S.CURRENT_STOCK, SALES.QTY_SL, POS.QTY_OUTSTANDING
FROM PRODUCTS P
LEFT JOIN STOCK S
ON S.REF = P.REF
LEFT JOIN SALES SALES
ON SALES.REF = P.REF
LEFT JOIN POS
ON POS.REF = P.REF

答案 2 :(得分:0)

假设REF 唯一并在所有表格中像外键一样使用

也许你可以试试

SELECT pt.REF, pt.DESCRIPTION, st.CURRENT_STOCK, sat.QTY_SOLD, pot.QTY_OUTSTANDING
FROM PRODUCTTABLE pt
INNER JOIN STOCKTABLE st
ON st.REF = pt.REF
INNER JOIN SALESTABLE sat
ON sat.REF = pt.REF
INNER JOIN POSTABLE pot
ON pot.REF = pt.REF

我很喜欢这个Graphical summary of join operations非常有用!