LeetCode-1322. Advertising effectiveness (simple) ifnull

Table: Ads

+ --------- + --------------- +
| Column the Name | Type |
+ --------------- + + ---------
| ad_id | int |
| user_id | int |
| Action | enum |
+ --------------- + -------- - +
(ad_id, user_id) is the primary key of the table
for each row of the table contains an advertisement ID (ad_id), user ID (user_id) and behavior (action) user ad take
action column is an enumerated type ( 'Clicked', 'Viewed', 'Ignored').
 

One company is operating these ads and want to calculate the performance of each ad.

Advertising effectiveness using click-through rates (Click-Through Rate: CTR) to measure the following formula:

Write a SQL statement to query ctr each ad,

 ctr to two decimal places. The results required by the descending ctr, press ad_id ascending order.

 

Example query results are as follows:

Ads 表:
+-------+---------+---------+
| ad_id | user_id | action  |
+-------+---------+---------+
| 1     | 1       | Clicked |
| 2     | 2       | Clicked |
| 3     | 3       | Viewed  |
| 5     | 5       | Ignored |
| 1     | 7       | Ignored |
| 2     | 7       | Viewed  |
| 3     | 5       | Clicked |
| 1     | 4       | Viewed  |
| 2     | 11      | Viewed  |
| 1     | 2       | Clicked |
+-------+---------+---------+
结果表:
+-------+-------+
| ad_id | ctr   |
+-------+-------+
| 1     | 66.67 |
| 3     | 50.00 |
| 2     | 33.33 |
| 5     | 0.00  |
+ ------- + ------- +
for ad_id = 1, ctr = (2 / (2 + 1)) * 100 = 66.67
for ad_id = 2, ctr = (1 / (1+ 2)) * 100 = 33.33
for ad_id = 3, ctr = (1 / (1 + 1)) * 100 = 50.00
for ad_id = 5, ctr = 0.00, note ad_id = 5 not clicked (the clicked) or view (Viewed ) over the
note that we do not care for the advertising action Ingnored the
results by ctr (in descending order), ad_id (ascending order)

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/ads-performance
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Moderation:
thinking:

Problem solving:

SELECT ad_id,IFNULL(ROUND(SUM(action = 'Clicked')/(SUM(action = 'Clicked')+SUM(action = 'Viewed'))*100,2),0) AS ctr
FROM Ads
GROUP BY ad_id
ORDER BY ctr DESC,ad_id

Knowledge Point: ifnull

Published 144 original articles · won praise 2 · Views 5732

Guess you like

Origin blog.csdn.net/Hello_JavaScript/article/details/104784148