【问题标题】:SQL: select max value when converting from long to wide formatSQL:从长格式转换为宽格式时选择最大值
【发布时间】:2020-12-13 15:40:24
【问题描述】:

我有一个如下表,我需要将它从这个长格式转换为宽格式,同时我需要选择与最高分数对应的动作值:

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 列。

【问题讨论】:

  • 第一行不应该是0.70.40.3而不是0.60.30.3吗?
  • 你如何计算action_value?从例子中看不清楚。
  • 添加你的数据库类型并解释你如何计算action_value
  • val0, val1, val2 是 action_value 的 one-hot 编码版本。我也编辑了错字

标签: sql group-by pivot


【解决方案1】:

您可以使用子查询,然后使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多