我应该自我加入吗

Should I do a self join

我有一个 table 以一种非常奇怪的方式存储信息。每个条目在数据库中有 4 行。它们由 ROW_ID 字段链接,每个条目然后在 1-4 之间有一个 column_id,表示值进入

的列
Row_id          Column_id         Value
1               1                 Value1
1               2                 Value2
1               3                 Value3
1               4                 Value4

目前正在通过对每个值的查询提取此信息,这些值被放入 excel 传播 sheet 但它需要 4 个单独的查询,每个查询都有每个列的信息

select value from table where column_id =1 order by row_id;
select value from table where column_id =2 order by row_id;
select value from table where column_id =3 order by row_id;
select value from table where column_id =4 order by row_id;

这都能一行输出吗?

        Column_id1    Column_id2     Column_id3     Column_id4
Row_id  Value1        Value2         Value3         Value4

您可以使用条件聚合、自连接或 pivot。我更喜欢前者:

select row_id,
       max(case when column_id = 1 then value end) as value_1,
       max(case when column_id = 2 then value end) as value_2,
       max(case when column_id = 3 then value end) as value_3,
       max(case when column_id = 4 then value end) as value_4
from t
group by row_id;