我有一个场景,我需要找到最佳和最差的团队以及每个问题类别的得分。下面是输入表。
输出应为:
我尝试了查询,但无法找到最好和最差的团队。
SELECT QUESTION_CATEGORY,TEAM_NAME ,MIN(MARKS) WORST_SCORE,MAX(MARKS) BEST_SCORE,
FROM QUESTIONS GROUP BY QUESTION_CATEGORY,TEAM_NAME
答案 0 :(得分:3)
这可以使用row_numbers以升序和降序以及条件聚合来完成。
SELECT QUESTION_CATEGORY
,MAX(CASE WHEN RN_DESC=1 THEN TEAM_NAME END) AS BEST_TEAM
,MAX(CASE WHEN RN_DESC=1 THEN MARKS END) AS BEST_MARKS
,MAX(CASE WHEN RN_ASC=1 THEN TEAM_NAME END) AS WORST_TEAM
,MAX(CASE WHEN RN_ASC=1 THEN MARKS END) AS WORST_MARKS
FROM (SELECT QUESTION_CATEGORY,TEAM_NAME
,ROW_NUMBER() OVER(PARTITION BY QUESTION_CATEGORY ORDER BY MARKS) as RN_ASC
,ROW_NUMBER() OVER(PARTITION BY QUESTION_CATEGORY ORDER BY MARKS DESC) as RN_DESC
FROM QUESTIONS
) T
GROUP BY QUESTION_CATEGORY
如果在最高/最低分数中可以存在关系,请在ORDER BY
ROW_NUMBER
函数中添加打破平局条件。
答案 1 :(得分:3)
尝试使用此方法获得所需结果,而不使用子查询:
SELECT
QUESTION_CATEGORY,
MIN(TEAM_NAME) KEEP (DENSE_RANK LAST ORDER BY MARKS) AS BEST_TEAM,
MIN(TEAM_NAME) KEEP (DENSE_RANK FIRST ORDER BY MARKS) AS WORST_TEAM,
MIN(MARKS) WORST_SCORE,
MAX(MARKS) BEST_SCORE,
FROM QUESTIONS
GROUP BY QUESTION_CATEGORY;
请参阅FIRST文档
答案 2 :(得分:2)
未经测试,但我会尝试这条道路:
select question_category, team_name, marks
from questions
where marks in (select max(marks)
from questions q1
where q1.question_category = questions.question_category)
or marks in (select min(marks)
from questions q1
where q1.question_category = questions.question_category)