鉴于下表,该表跟踪每个广告系列的点击和观看次数:
record_id advert_id type
-----------------------------------
1 100 click
2 102 click
3 100 view
4 100 view
5 102 view
6 100 view
7 101 view
8 101 click
是否可以通过单个查询汇总点击次数和观看次数,即看起来像这样:
advert_id clicks views
-------------------------------
100 1 3
101 1 1
102 1 1
答案 0 :(得分:1)
按advert_id
分组并使用条件聚合
select advert_id,
sum(type = 'click') as clicks,
sum(type = 'view') as views
from your_table
group by advert_id
答案 1 :(得分:1)
GROUP BY
上advert_id
。这样,您就可以将特定advert_id
的结果汇总到一行中。type
上使用Case .. When
表达式来有条件地检查其值是click
还是type
,并相应地Count()
点击和观看分别。请尝试以下操作:
SELECT
advert_id
COUNT(CASE WHEN type = 'click' THEN 1 END) AS clicks,
COUNT(CASE WHEN type = 'view' THEN 1 END) AS views
FROM your_table
GROUP BY advert_id