1211. Queries Quality and Percentage
Table: Queries
Column Name | Type |
---|---|
query_name | varchar |
result | varchar |
position | int |
rating | int |
This table may have duplicate rows.
This table contains information collected from some queries on a database.
The position column has a value from 1 to 500.
The rating column has a value from 1 to 5. Query with rating less than 3 is a poor query.
Instructions
NOTES:
- We define query
quality
as the average of the ratio between query rating and its position. - We also define
poor query percentage
as the percentage of all queries with rating less than 3.
- Write a solution to find each
query_name
, thequality
andpoor_query_percentage
. - Both
quality
andpoor_query_percentage
should be rounded to two (2) decimal places. - Return the result table in any order.
- The result format is in the following example.
Example
Input: Queries
table
query_name | result | position | rating |
---|---|---|---|
Dog | Golden Retriever | 1 | 5 |
Dog | German Shepherd | 2 | 5 |
Dog | Mule | 200 | 1 |
Cat | Shirazi | 5 | 2 |
Cat | Siamese | 3 | 3 |
Cat | Sphynx | 7 | 4 |
Output:
query_name | quality | poor_query_percentage |
---|---|---|
Dog | 2.50 | 33.33 |
Cat | 0.66 | 33.33 |
Explanation:
Dog queries
quality
is. Dog queries
poor_query_percentage
is. Cat queries
quality
equals. Cat queries
poor_query_percentage
is.
Submissions
sql
SELECT
query_name,
ROUND(AVG(rating * 1.0 / position), 2) AS quality,
ROUND(SUM(CASE WHEN rating < 3 THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS poor_query_percentage
FROM
Queries
WHERE
query_name IS NOT NULL
GROUP BY
query_name;
Explanations
PostgreSQL
Submitted by @noeyislearning
SELECT query_name
: Select thequery_name
from theQueries
table.ROUND(AVG(rating * 1.0 / position), 2) AS quality
: Calculate thequality
by getting the average of the ratio betweenrating
andposition
and round it to two decimal places.ROUND(SUM(CASE WHEN rating < 3 THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS poor_query_percentage
: Calculate thepoor_query_percentage
by getting the sum of queries with a rating less than 3, multiplying it by 100.0, dividing it by the total count of queries, and round it to two decimal places.
FROM Queries
: Select theQueries
table.WHERE query_name IS NOT NULL
: Filter out the rows wherequery_name
is not null.GROUP BY query_name
: Group the result byquery_name
.