【问题标题】:sql: long to wide format without using PIVOTsql:不使用 PIVOT 的长到宽格式
【发布时间】:2020-12-13 15:19:35
【问题描述】:

我有一张如下表:

user_id time_id val0 val1 val2 actual_value score
1       1       1    0     0   0           0.6
1       1       0    1     0   1           0.4
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.9
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
1       1           0.6.    0.3.    0.3
1       2           0.7.    0.4.    0.3
2       1           0.9.    0.5.    0.4

我使用的 SQL 没有枢轴选择,所以我想知道如何在不使用 PIVOT 的情况下将长格式转换为宽格式。

【问题讨论】:

  • 为什么会删除有效的cmets?目前尚不清楚第一行是如何实现的。其他用户指出但已被删除。

标签: sql database group-by pivot


【解决方案1】:

如果我正确理解您的问题,您可以进行条件聚合:

select
    user_id,
    time_id,
    max(case when val0 = 1 then score end) score0,
    max(case when val1 = 1 then score end) score1,
    max(case when val2 = 1 then score end) score2
from mytable
group by user_id, time_id

也许您想使用 actual_value 而不是 val[n] 列进行透视:

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

【讨论】:

    【解决方案2】:

    您可以使用条件聚合:

    select user_id, time_id,
           max(case when actual_value = 0 then score end) as score_0,
           max(case when actual_value = 1 then score end) as score_1,
           max(case when actual_value = 2 then score end) as score_2
    from t
    group by user_id, time_id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多