SQL 通过匹配 id 查询组数据并为唯一值添加新列

SQL query group data by matching id and add new columns for unique values

当前数据集:

USER_ID FEATURE_ID FEATURE_ID_VALUE
123 1 TRUE
321 1 FALSE
123 2 SomeText
321 2 AnotherOne
123 3 MoreText
321 3 EvenMore

我希望能够在 SQL 查询中转换此数据集以生成如下内容:

USER_ID FEATURE_ID_1 FEATURE_ID_2 FEATURE_ID_3
123 TRUE SomeText MoreText
321 FALSE AnotherOne EvenMore

我研究过使用 Pivots 和 Group By 函数,但我自己想不出一些有效的方法。

你可以使用 case 语句

这里是fiddlehttps://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=025750c52c92080b72b34688a60ba609

select user_id, 
max(case feature_id when 1 then feature_id_value else null end) as Feature_ID_1,
max(case feature_id when 2 then feature_id_value else null end) as Feature_ID_2,
max(case feature_id when 3 then feature_id_value else null end) as Feature_ID_3
 from mytable group by user_id

您可以使用 PIVOT:

SELECT *
FROM   table_name
PIVOT (
  MAX(feature_id_value)
  FOR FEATURE_ID IN (
    1 AS feature_id_1,
    2 AS feature_id_2,
    3 AS feature_id_3
  )
)

其中,对于示例数据:

CREATE TABLE table_name (USER_ID, FEATURE_ID, FEATURE_ID_VALUE) AS
SELECT 123, 1, 'TRUE'       FROM DUAL UNION ALL
SELECT 321, 1, 'FALSE'      FROM DUAL UNION ALL
SELECT 123, 2, 'SomeText'   FROM DUAL UNION ALL
SELECT 321, 2, 'AnotherOne' FROM DUAL UNION ALL
SELECT 123, 3, 'MoreText'   FROM DUAL UNION ALL
SELECT 321, 3, 'EvenMore'   FROM DUAL;

输出:

USER_ID FEATURE_ID_1 FEATURE_ID_2 FEATURE_ID_3
123 TRUE SomeText MoreText
321 FALSE AnotherOne EvenMore

db<>fiddle here