【发布时间】:2014-11-23 08:00:31
【问题描述】:
我有两张桌子
mysql> select * from report;
+----+----------+------------+------------------+-------------+
| id | campaign | advertiser | impression_count | click_count |
+----+----------+------------+------------------+-------------+
| 1 | camp1 | adv1 | 20 | 6 |
| 2 | camp2 | adv2 | 10 | 2 |
| 3 | camp1 | adv1 | 15 | 3 |
| 4 | camp2 | adv2 | 6 | 1 |
+----+----------+------------+------------------+-------------+
4 rows in set (0.00 sec)
mysql> select * from device;
+-----------+-----------+
| report_id | device_id |
+-----------+-----------+
| 1 | d1 |
| 1 | d2 |
| 2 | d1 |
| 2 | d3 |
| 2 | d4 |
| 3 | d2 |
| 3 | d4 |
| 4 | d3 |
| 4 | d4 |
| 4 | d5 |
+-----------+-----------+
10 rows in set (0.00 sec)
我想要在广告系列和广告客户级别汇总的报告,其中包含展示次数和点击次数的总和以及不同的 device_id。所以我写了下面的查询
SELECT
campaign,
advertiser,
sum(impression_count),
sum(click_count),
count(DISTINCT device_id)
FROM report
LEFT JOIN device ON report.id = device.report_id
GROUP BY campaign, advertiser;
+----------+------------+-----------------------+------------------+---------------------------+
| campaign | advertiser | sum(impression_count) | sum(click_count) | count(distinct device_id) |
+----------+------------+-----------------------+------------------+---------------------------+
| camp1 | adv1 | 70 | 18 | 3 |
| camp2 | adv2 | 48 | 9 | 4 |
+----------+------------+-----------------------+------------------+---------------------------+
这里是因为加入展示次数和 click_count 是为多行聚合的。想要的是
+----------+------------+-----------------------+------------------+---------------------------+
| campaign | advertiser | sum(impression_count) | sum(click_count) | count(distinct device_id) |
+----------+------------+-----------------------+------------------+---------------------------+
| camp1 | adv1 | 35 | 9 | 3 |
| camp2 | adv2 | 16 | 3 | 4 |
+----------+------------+-----------------------+------------------+---------------------------+
http://sqlfiddle.com/#!2/05dd9d/1
发现不是很好的解决方案
select campaign,advertiser,ic,cc,count(distinct device_id)
from (
select
group_concat(id) as id,
sum(impression_count)as ic,
sum(click_count)as cc,
campaign,advertiser
FROM report har GROUP BY campaign,advertiser) a
LEFT JOIN device dr ON FIND_IN_SET(dr.report_id, a.id)
group by a.id
);
但是这使用了组 concat,所以如果 group_concat 结果的长度很大,可能会出现问题。
【问题讨论】:
-
请更新SQL Fiddle中的表架构