1
+ -- 1211. Queries Quality and Percentage
2
+ -- Easy
3
+ -- https://leetcode.com/problems/queries-quality-and-percentage
4
+
5
+ /*
6
+ Table: Queries
7
+ +-------------+---------+
8
+ | Column Name | Type |
9
+ +-------------+---------+
10
+ | query_name | varchar |
11
+ | result | varchar |
12
+ | position | int |
13
+ | rating | int |
14
+ +-------------+---------+
15
+ There is no primary key for this table, it may have duplicate rows.
16
+ This table contains information collected from some queries on a database.
17
+ The position column has a value from 1 to 500.
18
+ The rating column has a value from 1 to 5. Query with rating less than 3 is a poor query.
19
+ We define query quality as:
20
+ The average of the ratio between query rating and its position.
21
+ We also define poor query percentage as:
22
+ The percentage of all queries with rating less than 3.
23
+ Write an SQL query to find each query_name, the quality and poor_query_percentage.
24
+ Both quality and poor_query_percentage should be rounded to 2 decimal places.
25
+ Return the result table in any order.
26
+ The query result format is in the following example.
27
+
28
+ Example 1:
29
+ Input:
30
+ Queries table:
31
+ +------------+-------------------+----------+--------+
32
+ | query_name | result | position | rating |
33
+ +------------+-------------------+----------+--------+
34
+ | Dog | Golden Retriever | 1 | 5 |
35
+ | Dog | German Shepherd | 2 | 5 |
36
+ | Dog | Mule | 200 | 1 |
37
+ | Cat | Shirazi | 5 | 2 |
38
+ | Cat | Siamese | 3 | 3 |
39
+ | Cat | Sphynx | 7 | 4 |
40
+ +------------+-------------------+----------+--------+
41
+ Output:
42
+ +------------+---------+-----------------------+
43
+ | query_name | quality | poor_query_percentage |
44
+ +------------+---------+-----------------------+
45
+ | Dog | 2.50 | 33.33 |
46
+ | Cat | 0.66 | 33.33 |
47
+ +------------+---------+-----------------------+
48
+ Explanation:
49
+ Dog queries quality is ((5 / 1) + (5 / 2) + (1 / 200)) / 3 = 2.50
50
+ Dog queries poor_ query_percentage is (1 / 3) * 100 = 33.33
51
+ Cat queries quality equals ((2 / 5) + (3 / 3) + (4 / 7)) / 3 = 0.66
52
+ Cat queries poor_ query_percentage is (1 / 3) * 100 = 33.33
53
+ */
54
+
55
+ SELECT
56
+ query_name,
57
+ ROUND(AVG (1 .0 * rating / position), 2 ) AS quality,
58
+ ROUND(100 * SUM (CASE WHEN rating < 3 THEN 1 ELSE 0 END)/ COUNT (* ), 2 ) AS poor_query_percentage
59
+ FROM
60
+ Queries
61
+ GROUP BY
62
+ query_name;
0 commit comments