SQL Group By和;内部联接

时间:2012-04-02 06:58:47

标签: sql group-by

SELECT
   C.SOId, Ser.TotalService, S.TotalSales 
FROM
  salesorder C
  INNER JOIN  (SELECT SOId,SUM(charge) as TotalService FROM sales_serviceline GROUP BY SOId)  Ser
  ON C.SOId = Ser.SOId
  INNER JOIN  (SELECT SOId,SUM(PriceEach*qty) as TotalSales FROM  salesline  GROUP BY  SOId)  S
  ON C.SOId = S.SOId

说明: 一个SalesOrder有许多销售线 一个SalesOrder有许多销售线服务

因此,如果销售订单具有saleslins& salesline_service然后上面的查询成功地检索了该销售订单的总金额,但是如果只有盐水线或仅销售线服务没有重试销售订单,如何更改此查询以获得所有结果?

1 个答案:

答案 0 :(得分:3)

我认为您正在寻找LEFT JOIN。如果SerS中没有行,那么LEFT JOINTotalServiceTotalSales NULL

SELECT
   C.SOId, Ser.TotalService, S.TotalSales 
FROM
  salesorder C
  LEFT JOIN  (SELECT SOId,SUM(charge) as TotalService FROM sales_serviceline GROUP BY SOId)  Ser
  ON C.SOId = Ser.SOId
  LEFT JOIN  (SELECT SOId,SUM(PriceEach*qty) as TotalSales FROM  salesline  GROUP BY  SOId)  S
  ON C.SOId = S.SOId

如果您不想将它们设为NULL。然后您可以退出轻松使用COALESCE()。像这样:

SELECT
   C.SOId, 
   COALESCE(Ser.TotalService,0) AS TotalService, 
   COALESCE(S.TotalSales,0) AS TotalSales
FROM
  salesorder C
  LEFT JOIN  (SELECT SOId,SUM(charge) as TotalService FROM sales_serviceline GROUP BY SOId)  Ser
  ON C.SOId = Ser.SOId
  LEFT JOIN  (SELECT SOId,SUM(PriceEach*qty) as TotalSales FROM  salesline  GROUP BY  SOId)  S
  ON C.SOId = S.SOId