计算Sum()但不包括JOIN

时间:2013-11-19 19:01:15

标签: mysql sql

sales表中,有一个point字段。我希望sum(point)sales.submit_date进行分组,但不会正确添加,因为它会复制来自JOIN的记录

SELECT 
    COUNT(DISTINCT sales.sales_id) as TotalSales, 
    COUNT(DISTINCT sales_lines.id) as TotalLiness
FROM `sales` 
    JOIN sales_lines ON sales_lines.sales_id = sales.sales_id
GROUP BY sales.submit_date

上面的SQL,这将计算sales表中的销售数量,并计算sales_lines中的行数(与sales_lines.sales_id = sales.sales_id匹配的行数)。这似乎工作正常。

如何仅在销售中汇总(`sales.point')?

1 个答案:

答案 0 :(得分:1)

您可以将sales_lines汇总到销售谷物。

SELECT
  S.submit.date,
  ,sum(s.point)
  ,COUNT(s.sales_id) as TotalSales
  ,SUM(SL.SalesLines) as TotalLines
FROM
 sales S
INNER JOIN 
(Select
  sales_id
  ,count(distinct id) as SalesLines
 FROM
   sales_lines
 GROUP BY
  sales_id) SL
ON S.sales_id = SL.sales_id3
GROUP BY
 s.submit_date