力扣高频SQL 50题(基础版)第十九题
1211. 查询结果的质量和占比
题目说明
Queries
表:
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| query_name | varchar |
| result | varchar |
| position | int |
| rating | int |
+-------------+---------+
此表可能有重复的行。
此表包含了一些从数据库中收集的查询信息。
“位置”(position)列的值为 1 到 500 。
“评分”(rating)列的值为 1 到 5 。评分小于 3 的查询被定义为质量很差的查询。
将查询结果的质量 quality
定义为:
各查询结果的评分与其位置之间比率的平均值。
将劣质查询百分比 poor_query_percentage
为:
评分小于 3 的查询结果占全部查询结果的百分比。
编写解决方案,找出每次的 query_name
、 quality
和 poor_query_percentage
。
quality
和 poor_query_percentage
都应 四舍五入到小数点后两位 。
以 任意顺序 返回结果表。
思路分析
实现过程
准备数据
Create table If Not Exists Queries (query_name varchar(30), result varchar(50), position int, rating int)
Truncate table Queries
insert into Queries (query_name, result, position, rating) values ('Dog', 'Golden Retriever', '1', '5')
insert into Queries (query_name, result, position, rating) values ('Dog', 'German Shepherd', '2', '5')
insert into Queries (query_name, result, position, rating) values ('Dog', 'Mule', '200', '1')
insert into Queries (query_name, result, position, rating) values ('Cat', 'Shirazi', '5', '2')
insert into Queries (query_name, result, position, rating) values ('Cat', 'Siamese', '3', '3')
insert into Queries (query_name, result, position, rating) values ('Cat', 'Sphynx', '7', '4')
实现方式
# 方法一:
with t1 as (
select
query_name,
count(*) AS total_count, -- 计算每个query_name的总数
sum(case when rating < 3 then 1 else 0 end) as poor_count -- 计算rating小于3的查询数
from
Queries
group by
query_name
),
t2 as (
select
query_name,
sum(rating * 1.0 / position) as total_quality
from
Queries
group by
query_name
)
select
q.query_name,
round(t2.total_quality / t1.total_count, 2) as quality, -- 计算平均质量
ROUND(t1.poor_count * 100 / t1.total_count, 2) as poor_query_percentage -- 计算劣质查询百分比
from
Queries q
join
t1 on q.query_name = t1.query_name
join
t2 on q.query_name = t2.query_name
group by
q.query_name, t1.total_count, t1.poor_count, t2.total_quality;
#方法二
WITH t1 AS (
SELECT
query_name,
COUNT(*) AS total_count, -- 计算每个query_name的总数
SUM(CASE WHEN rating < 3 THEN 1 ELSE 0 END) AS poor_count -- 计算rating小于3的查询数
FROM
Queries
GROUP BY
query_name
),
t2 AS (
SELECT
query_name,
SUM(rating * 1.0 / position) AS total_quality
FROM
Queries
GROUP BY
query_name
)
SELECT
t1.query_name,
ROUND(t2.total_quality / t1.total_count, 2) AS quality, -- 计算平均质量
ROUND(t1.poor_count * 100 / t1.total_count, 2) AS poor_query_percentage -- 计算劣质查询百分比
FROM
t1
JOIN
t2 ON t1.query_name = t2.query_name;