评级表中的数据如下所示:

StudentID Rating ScoreType Date
1 12 RAPID 2023-01-01
1 15 RAPID 2023-01-10
1 20 RAPID 2023-02-15
1 25 RAPID 2023-02-20
1 25 BLITZ 2023-03-01
1 33 BLITZ 2023-03-20
2 17 RAPID 2023-01-15
2 19 BLITZ 2023-02-06

我正在try 构建的是这样的:

StudentID RAPID_Rating RAPID_Games BLITZ_Rating BLITZ_Games Total Games
1 25 4 33 2 6
2 17 1 19 1 2

每个学生的数据应该是一行

预期输出的列定义:

RAPID_RATING:基于ScoreType=‘RAPID’的日期的最新评级值

Rapid_Games:每个学生玩的快速游戏的总数

Blitz_Rating:基于日期的最新评价值,其中ScoreType=‘blitz’

Flitz_Games:每个学生玩的BLIRZ游戏总数

游戏总数:每个学生玩的游戏总数

我try 过的SQL代码:

select
    coalesce(a.StudentID,b.StudentID) as StudentID,
    a.rating as RAPID_Rating,
    RAPID_Games,
    b.rating as BLITZ_Rating,
    BLITZ_Games,
    RAPID_Games + BLITZ_Games as Total_Games
    
from 
(select 
    StudentID, 
    ScoreType,
    rating,
    count(rating) over(partition by StudentID,ScoreType) as RAPID_Games,
    row_number() over(partition by StudentID,ScoreType order by date desc) as RNUM
from rating 
    where ScoreType ='RAPID'
) a join (
    select 
    StudentID, 
    ScoreType,
    rating,
    count(rating) over(partition by StudentID,ScoreType) as BLITZ_Games,
    row_number() over(partition by StudentID,ScoreType order by date desc) as RNUM
from rating 
    where ScoreType ='BLITZ'
) b on a.StudentID = b.StudentID 
where a.RNUM = 1 and b.RNUM = 1

我必须为另外2个类别做这个计算,然后再加起来2个子查询.有什么办法可以优化这段SQL代码吗?

推荐答案

我们可以在这里使用ROW_NUMBER和条件聚合:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY StudentID, ScoreType ORDER BY Date DESC) rn
    FROM rating
)

SELECT
    StudentID,
    MAX(Rating) FILTER (WHERE ScoreType = 'RAPID' AND rn = 1) AS RAPID_Rating,
    COUNT(*) FILTER (WHERE ScoreType = 'RAPID') AS RAPID_Games,
    MAX(Rating) FILTER (WHERE ScoreType = 'BLITZ' AND rn = 1) AS BLITZ_Rating,
    COUNT(*) FILTER (WHERE ScoreType = 'BLITZ') AS BLITZ_Games,
    COUNT(*) AS "Total Games"
FROM cte
GROUP BY StudentID
ORDER BY StudentID;

Sql相关问答推荐

帮助修复查询以识别SQL DW中数据中的递归关系

如何在T—SQL中找到值更改之前的日期?

对于表A中的每一行,更新表B中与金额有关的行

在postgres中动态计算出现次数并插入到json中

Access 365将文本转换回BigInt

检索上一个星期四和上一个星期三

对列进行排序后,基于两列删除重复行

需要从键-值对数据中提取值

Postgres SQL查询从字符串中获取邮箱地址

组合2个分区表的postgres视图的执行计划正在访问所有分区

将伪数据插入Postgres表

如何对 jsonb 中的字段执行求和,然后使用结果过滤查询的输出

每次计数器增加时通过运行总重置进行分组

在没有订单的情况下,如何生成一个值为0的顾客天数行

Postgres更新增量之间的差异

检索具有相同位置的最小和最大store 数量

PostgreSQL:通过数组的元素从另一个表中 Select 数据,然后按顺序显示

如何按日期和位置对最近 3 个报告日期的 SQL 查询结果进行透视?

并非所有变量都绑定在 PL SQL 函数中

Lag() 获取snowflake的值变化