12

我有两张桌子:

具有某些字段和主键 ID 的经销商

并使用以下字段 id 查询 Dealer_id 费用

每个经销商都有几个项目要查询,我必须计算它们并计算成本。现在我只有这个语句的计数:

SELECT a.*, Count(b.id) as counttotal
FROM dealers a
LEFT JOIN inquiries b on a.id=b.dealer_id
GROUP BY a.id
ORDER BY name ASC

但我不知道如何为每个经销商汇总表 b 的成本。有人可以帮忙吗?提前致谢

4

6 回答 6

20

您可以使用两个子查询:

SELECT  a.*
      , (SELECT Count(b.id) FROM inquiries I1 WHERE I1.dealer_id = a.id) as counttotal
      , (SELECT SUM(b.cost) FROM inquiries I2 WHERE I2.dealer_id = a.id) as turnover
FROM dealers a
ORDER BY name ASC

或者

SELECT  a.*
     , COALESCE(T.counttotal, 0) as counttotal   -- use coalesce or equiv. to turn NULLs to 0
     , COALESCE(T.turnover, 0) as turnover       -- use coalesce or equiv. to turn NULLs to 0
 FROM dealers a
 LEFT OUTER JOIN (SELECT a.id, Count(b.id) as counttotal, SUM(b.cost) as turnover
               FROM dealers a1 
               INNER JOIN inquiries b ON a1.id = b.dealer_id
              GROUP BY a.id) T
         ON a.id = T.id
ORDER BY a.name
于 2013-03-13T14:17:56.107 回答
4
SELECT a.*, Sum(b.id) as TotalCost
FROM dealers a
LEFT JOIN inquiries b on a.id=b.dealer_id
GROUP BY a.id
ORDER BY name ASC
于 2013-03-13T14:24:26.440 回答
2

如果我理解您的问题,您需要做的就是添加SUM()

SELECT a.*, 
  Count(b.id) as counttotal,
  sum(b.costs) TotalCost
FROM dealers a
LEFT JOIN inquiries b on a.id=b.dealer_id
GROUP BY a.id
ORDER BY name ASC

我的建议是使用子查询来获取countsum

SELECT a.*, 
  b.countTotal,
  b.TotalCosts
FROM dealers a
LEFT JOIN
(
    select COUNT(ID) countTotal,
        SUM(costs) TotalCosts,
        dealer_id
    from inquiries
    group by dealer_id
) b 
    on a.id=b.dealer_id
ORDER BY name ASC

我从您的原始查询中猜测您正在使用 MySQL。我建议使用子查询,因为 MySQL 使用 GROUP BY 的扩展,它允许选择列表中的项目不聚合并且不包含在GROUP BY子句中。然而,这可能会导致意外的结果,因为 MySQL 可以选择返回的值。(参见MySQL 对 GROUP BY 的扩展

来自 MySQL 文档:

MySQL 扩展了 GROUP BY 的使用,以便选择列表可以引用未在 GROUP BY 子句中命名的非聚合列。...您可以使用此功能通过避免不必要的列排序和分组来获得更好的性能。但是,这主要在每个未在 GROUP BY 中命名的非聚合列中的所有值对于每个组都相同时很有用。服务器可以从每个组中自由选择任何值,因此除非它们相同,否则选择的值是不确定的。此外,从每个组中选择值不会受到添加 ORDER BY 子句的影响。在选择了值之后对结果集进行排序,并且 ORDER BY 不会影响服务器选择的值。

于 2013-03-13T14:18:30.620 回答
2
SELECT a.*, COUNT(b.id) AS counttotal, SUM(b.costs) AS total
FROM dealers AS a
LEFT JOIN inquiries AS b ON a.id=b.dealer_id
GROUP BY a.id
ORDER BY name ASC
于 2013-03-13T14:21:23.113 回答
0

只需添加, Sum(b.costs) as costsTotal到您的选择列表中。

于 2013-03-13T14:18:17.630 回答
0

制作一个带有所需字段的子表并加入它,而不是完整的表将使事情变得更容易

从经销商中选择 a.*、b.count_total、b.costs_of_table
作为
LEFT JOIN (

SELECT aux.dealer_id, Count(aux.id) AS 'count_total', Sum(aux.costs) AS 'costs_of_table'
FROM 查询 AS aux
GROUP BY Dealer_id)

AS b ON a.id = b.dealer_id
WHERE(你想要什么)按
名称排序 ASC

对不起,如果有的话,酒吧拼写

于 2013-03-13T14:37:57.733 回答