我有两张桌子:
经销商 包含一些字段和主键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的成本加起来。有人可以帮忙吗?提前致谢
答案 0 :(得分:13)
您可以使用两个子查询:
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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分:1)
如果我理解您的问题,您需要做的只是添加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
我的建议是使用子查询来获取count
和sum
:
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 Extensions to GROUP BY)
来自MySQL文档:
MySQL扩展了GROUP BY的使用,因此选择列表可以引用GROUP BY子句中未命名的非聚合列。 ...您可以通过避免不必要的列排序和分组来使用此功能来获得更好的性能。但是,当GROUP BY中未命名的每个非聚合列中的所有值对于每个组都相同时,这非常有用。服务器可以自由选择每个组中的任何值,因此除非它们相同,否则所选的值是不确定的。此外,添加ORDER BY子句不会影响每个组中值的选择。选择值后会对结果集进行排序,而ORDER BY不会影响服务器选择的值。
答案 4 :(得分:0)
只需将, Sum(b.costs) as costsTotal
添加到您的选择列表中即可。
答案 5 :(得分:0)
制作一个带有所需字段的子表,然后加入它,而不是完整的表格会使事情更容易
选择a。*,b.count_total,b.costs_of_table
来自经销商AS a LEFT JOIN(SELECT aux.dealer_id,Count(aux.id)AS'count_total',Sum(aux.costs)AS'costs_of_table'
来自查询AS aux
GROUP BY dealer_id)AS b ON a.id = b.dealer_id
在哪里(你想要的)
ORDER BY name ASC
对不起,如果有任何
的条形码拼写