我们从这个查询得到了下面的结果表,但是我们如何添加一个汇总行来对同一个广告id的所有天数求和,如所需的结果表中所示?谢谢。
查询:
SELECT
right(ad_id,6) AS ad_id,
CAST(date_start AS DATE) AS "Day",
objective,
SUM(impressions) AS Impressions,
sum(clicks) AS Clicks
FROM ads
WHERE date_start >= '2018-05-01' AND date_start < '2018-06-01'
GROUP BY ad_id, CAST(date_start AS DATE), objective
Order by ad_id, CAST(date_start AS DATE) desc
结果表:
+--------+----------+-------------+-------------+--------+
| ad_id | day | objective | impressions | clicks |
+--------+----------+-------------+-------------+--------+
| 36911 | 5/2/2018 | CONVERSIONS | 16689 | 160 |
| 36911 | 5/1/2018 | CONVERSIONS | 4223 | 59 |
| 37111 | 5/2/2018 | CONVERSIONS | 1964 | 9 |
| 37111 | 5/1/2018 | CONVERSIONS | 1409 | 19 |
| 279311 | 5/3/2018 | LINK_CLICKS | 309 | 10 |
| 279311 | 5/2/2018 | LINK_CLICKS | 2816 | 19 |
| 279311 | 5/1/2018 | LINK_CLICKS | 5876 | 66 |
| 279511 | 5/3/2018 | LINK_CLICKS | 3551 | 86 |
| 279511 | 5/2/2018 | LINK_CLICKS | 3334 | 76 |
| 279511 | 5/1/2018 | LINK_CLICKS | 17798 | 508 |
+--------+----------+-------------+-------------+--------+
包含摘要行的所需结果表:
+--------+----------+-------------+-------------+--------+
| ad_id | day | objective | impressions | clicks |
+--------+----------+-------------+-------------+--------+
| 36911 | All | CONVERSIONS | 20912 | 219 |
| 36911 | 5/2/2018 | CONVERSIONS | 16689 | 160 |
| 36911 | 5/1/2018 | CONVERSIONS | 4223 | 59 |
| 37111 | All | CONVERSIONS | 3373 | 28 |
| 37111 | 5/2/2018 | CONVERSIONS | 1964 | 9 |
| 37111 | 5/1/2018 | CONVERSIONS | 1409 | 19 |
| 279311 | All | LINK_CLICKS | 9001 | 95 |
| 279311 | 5/3/2018 | LINK_CLICKS | 309 | 10 |
| 279311 | 5/2/2018 | LINK_CLICKS | 2816 | 19 |
| 279311 | 5/1/2018 | LINK_CLICKS | 5876 | 66 |
| 279511 | All | LINK_CLICKS | 24683 | 670 |
| 279511 | 5/3/2018 | LINK_CLICKS | 3551 | 86 |
| 279511 | 5/2/2018 | LINK_CLICKS | 3334 | 76 |
| 279511 | 5/1/2018 | LINK_CLICKS | 17798 | 508 |
+--------+----------+-------------+-------------+--------+
最佳答案
使用grouping sets
:
SELECT COALESCE(right(ad_id, 6), 'All') AS ad_id,
CAST(date_start AS DATE) AS "Day",
objective,
SUM(impressions) AS Impressions,
sum(clicks) AS Clicks
FROM ads
WHERE date_start >= '2018-05-01' AND date_start < '2018-06-01'
GROUP BY GROUPING SETS ( (ad_id), (ad_id, CAST(date_start AS DATE), objective) )
Order by ad_id, CAST(date_start AS DATE) desc;
在Postgres的早期版本中,使用CTE和
union all
:with t as (
SELECT right(ad_id, 6) AS ad_id,
CAST(date_start AS DATE) AS "Day",
objective,
SUM(impressions) AS Impressions,
sum(clicks) AS Clicks
FROM ads
WHERE date_start >= '2018-05-01' AND date_start < '2018-06-01'
GROUP BY GROUPING SETS (ad_id, CAST(date_start AS DATE), objective)
)
select *
from t
union all
select ad_id, NULL, 'All', sum(impressions), sum(clicks)
from t
group by ad_id
order by 1, 2 desc;