通过 group by 和 joins 获取多个表的多个列的总和
Posted
技术标签:
【中文标题】通过 group by 和 joins 获取多个表的多个列的总和【英文标题】:Getting Sum of multiple columns of multiple tables through group by and joins 【发布时间】:2012-03-09 05:35:42 【问题描述】:我正在使用以下查询使用左连接从两个表中获取多个列的总和。但是mysql显示“Error Code: 1111. Invalid use of group function”的错误请指出我哪里出错了?
SELECT url as Domain,
A.advertiserid as advertiserid,
count(A.salesId) as Impressions,
Sum(IF(A.click1datetime IS NULL,0,1)) AS Clicks,
sum(count(B.order_id)) as Sales,
sum(sum(B.order_amount)) as SalesAmount,
FROM ClickRecords A
left join SalesDetail B
on A.salesId= B.salesId
where
A.advertiserid = 52 AND
datetime >= '2012-03-01' AND
datetime < '2012-03-02'
group by advertiserid, Domain
order by impressions desc;
【问题讨论】:
这是因为您已经嵌套了总和 -SUM(COUNT
和 SUM(SUM
无效。您能否提供更多关于您的表如何相互关联以及为什么需要SUM(SUM(B.order_amount))
而不是SUM(B.order_amount)
以及SUM(COUNT(B.order_id))
的信息?
【参考方案1】:
如上所述,您不能嵌套聚合函数 - 即。 sum(sum(value))
无效。
我想你想要:
SELECT url as Domain,
A.advertiserid as advertiserid,
count(distinct A.salesId) as Impressions,
count(distinct case when A.click1datetime IS NOT NULL then A.salesId end)
AS Clicks,
count(B.order_id) as Sales,
sum(B.order_amount) as SalesAmount,
FROM ClickRecords A
left join SalesDetail B on A.salesId= B.salesId
where A.advertiserid = 52 AND
datetime >= '2012-03-01' AND
datetime < '2012-03-02'
group by advertiserid, Domain
order by impressions desc;
注意 count(distinct ...)
用于 ClickRecords 值 - sum
或非独特 count
根据非空记录的数量将值相加,这些记录可以乘以 SalesDetail 记录(其中有多个每点击记录)。
【讨论】:
【参考方案2】:您不能将聚合函数用作其他聚合函数的参数(例如:sum(count(B.order_id))
)。
【讨论】:
以上是关于通过 group by 和 joins 获取多个表的多个列的总和的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 join 和 group by 在 C# Linq 中获取 Min?
使用 MySQL 通过 JOIN 获取 GROUP BY 中的 SUM