mysql 查询:如何仅按 cpm.ad_id 进行分组并获得所有 cc 的总和?

发布于 2024-11-08 19:42:49 字数 861 浏览 0 评论 0原文

我有两个表 - cpmccad_idcpm)和 clicksccad_id)。

当我运行:

   SELECT cpm.ad_id, 
          COUNT(clicks.id) * cpm.cpm AS clicks_income     
     FROM cpm 
LEFT JOIN clicks on clicks.ad_id = cpm.ad_id and clicks.cc = cpm.cc
 GROUP BY cpm.ad_id, cpm.cc

我得到:

ad_id | clicks_income
---------------------
1     | 271.00
1     | 2.60
2     | 238.00

现在我想要的结果是:

ad_id | clicks_income
---------------------
1     | 273.60
2     | 238.00

如何仅按 cpm.ad_id 进行分组并获得所有 cc 的总和>?

当我删除 cpm.cc 时,我得到:

ad_id | clicks_income
---------------------
1     | 273.00
2     | 238.00

I have two tables - cpm(cc, ad_id and cpm) and clicks(cc and ad_id).

When I run:

   SELECT cpm.ad_id, 
          COUNT(clicks.id) * cpm.cpm AS clicks_income     
     FROM cpm 
LEFT JOIN clicks on clicks.ad_id = cpm.ad_id and clicks.cc = cpm.cc
 GROUP BY cpm.ad_id, cpm.cc

I get:

ad_id | clicks_income
---------------------
1     | 271.00
1     | 2.60
2     | 238.00

now the result I want is:

ad_id | clicks_income
---------------------
1     | 273.60
2     | 238.00

How can I group by only cpm.ad_id and having the SUM of all cc?

When I remove the cpm.cc I get:

ad_id | clicks_income
---------------------
1     | 273.00
2     | 238.00

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

厌倦 2024-11-15 19:42:49

不要使用 COUNT(whatever) * acolumn,而是使用 SUM(AColumn)
此外,LEFT JOIN 在这里没有意义,因为不匹配只会将 NULL 添加到总和中,这没有多大帮助。

SELECT cpm.ad_id, SUM(cpm.cpm) AS clicks_income 
FROM cpm INNER JOIN clicks ON clicks.ad_id = cpm.ad_id AND clicks.cc = cpm.cc
GROUP BY cpm.ad_id

Don't use COUNT(whatever) * acolumn, use SUM(AColumn) instead.
Also a LEFT JOIN doesn't make sense here because a mismatch will just add NULL to the sum, which isn't very helpful.

SELECT cpm.ad_id, SUM(cpm.cpm) AS clicks_income 
FROM cpm INNER JOIN clicks ON clicks.ad_id = cpm.ad_id AND clicks.cc = cpm.cc
GROUP BY cpm.ad_id
放我走吧 2024-11-15 19:42:49
SELECT cpm.ad_id, COUNT(clicks.id)*cpm.cpm AS clicks_income 
FROM cpm LEFT JOIN clicks ON clicks.ad_id = cpm.ad_id AND clicks.cc = cpm.cc
GROUP BY cpm.ad_id
SELECT cpm.ad_id, COUNT(clicks.id)*cpm.cpm AS clicks_income 
FROM cpm LEFT JOIN clicks ON clicks.ad_id = cpm.ad_id AND clicks.cc = cpm.cc
GROUP BY cpm.ad_id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文