汇总广告点击次数和观看次数

时间:2018-11-11 06:09:42

标签: mysql

鉴于下表,该表跟踪每个广告系列的点击和观看次数:

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

2 个答案:

答案 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 BYadvert_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