SQL分组表联接

时间:2018-10-03 22:17:09

标签: sql join sum

我正在努力弄清楚如何将两个分组表联接在一起,然后执行减法运算

我有这些表,其中包含以下列

表1:购买

供应商|数量|价格

表2:paysup

供应商|付费|

结果表

供应商|已购买总计PaidTotal |(已购买-已付款)|

我非常不正确的Sql查询

 SELECT t.Vendor, SUM(Quantity * Price) as TotalPurch
    FROM purchases t
    LEFT JOIN (SELECT Vendor, SUM(paid) as TotalPaid FROM paysup GROUP BY Vendor) y
    ON t.Vendor = y.Vendor
    GROUP BY t.Vendor

3 个答案:

答案 0 :(得分:0)

尝试一下:

SELECT COALESCE(a.Vendor, b.Vendor) AS Vendor
     , a.PurchasedTotal
     , b.PaidTotal
     , (COALESCE(a.PurchasedTotal, 0) - COALESCE(b.PaidTotal, 0)) AS "(Purchased - Paid)"
  FROM ( SELECT Vendor, SUM(Quantity * Price) AS PurchasedTotal
           FROM purchases
          GROUP BY Vendor
       ) a
  FULL JOIN ( SELECT Vendor, SUM(Paid) AS PaidTotal
                FROM paysup
               GROUP BY Vendor
       ) b ON b.Vendor = a.Vendor

答案 1 :(得分:0)

在这种情况下,通常有一个您不提及的供应商表

  SELECT v.Vendor
     , purch.PurchasedTotal
     , paid.PaidTotal
     , (COALESCE(purch.PurchasedTotal, 0) - COALESCE(paid.PaidTotal, 0)) AS "(Purchased - Paid)"
  FROM Vendors v
  LEFT JOIN ( SELECT Vendor, SUM(Quantity * Price) AS PurchasedTotal
              FROM purchases
              GROUP BY Vendor
             ) purch ON v.Vendor = purch.Vendor
  LEFT JOIN ( SELECT Vendor, SUM(Paid) AS PaidTotal
                FROM paysup
               GROUP BY Vendor
       ) paid ON v.Vendor = paid.Vendor
  ;

答案 2 :(得分:0)

您可以使用公用表表达式(CTE)来提高可读性:

WITH paid AS ( SELECT Vendor, SUM(Paid) AS PaidTotal
           FROM paysup
           GROUP BY Vendor
   ),
   purch AS ( SELECT Vendor, SUM(Quantity * Price) AS PurchasedTotal
          FROM purchases
          GROUP BY Vendor
   ) 
/* The main query: */
SELECT 
  v.Vendor, 
  purch.PurchasedTotal, 
  paid.PaidTotal, 
  (COALESCE(purch.PurchasedTotal, 0) - COALESCE(paid.PaidTotal, 0)) AS "(Purchased - Paid)"
 FROM Vendors v
  LEFT JOIN purch ON v.Vendor = purch.Vendor
  LEFT JOIN paid ON v.Vendor = paid.Vendor;