sql - SQL:从长格式转换为宽格式时选择最大值
问题描述
我有一个如下表,我需要将它从这种长格式转换为宽格式,同时,我需要选择对应于最高分数的动作值:
user_id time_id val0 val1 val2 action_value score
1 1 1 0 0 0 0.6
1 1 0 1 0 1 0.3
1 1 0 0 1 2 0.3
1 2 1 0 0 0 0.7
1 2 0 1 0 1 0.4
1 2 0 0 1 2 0.3
2 1 1 0 0 0 0.4
2 1 0 1 0 1 0.5
2 1 0 0 1 2 0.4
所需的输出是:
user_id time_id score_0 score_1 score_2 action_value
1 1 0.6. 0.3. 0.3 0
1 2 0.7. 0.4 0.3. 0
2 1 0.4 0.5 0.4. 1
我使用的 SQL 没有 PIVOT,所以我不能使用 PIVOT。而且我知道我可以使用条件聚合将数据从长格式转换为宽格式,但我不确定如何选择与最高分数对应的 action_value 列。
解决方案
您可以使用子查询,然后greatest()
(如果您的数据库支持它):
select
t.*,
case greatest(score0, score1, score2)
when score0 then 0
when score1 then 1
when score2 then 2
end action_value
from (
select
user_id,
time_id,
max(case when actual_value = 0 then score end) score0,
max(case when actual_value = 1 then score end) score1,
max(case when actual_value = 2 then score end) score2
from mytable
group by user_id, time_id
) t
推荐阅读
- javascript - 过滤 Typescript 中的现有对象属性
- java - 将数据输入 Firebase Android Studio 时出现重复错误
- database - 地图上点数据存储的最佳 AWS 云服务
- mysql - 如何显示被隐藏的行
- html - Angular i18n - 集合澄清的插值?
- bash - SSH 会话 - 为什么 bash FOR 循环甚至没有显示价值并且还使用 LOCAL 机器
- javascript - 比较 NodeJS IF 语句中的日期
- javascript - 如何获得 PathItems 的整数个数?(插画脚本)
- javascript - 如何将csv文件中的数据导入javascript字典?
- reactjs - 如何在 React Navigation v3 中创建动态选项卡