我有一个以非常奇怪的方式存储信息的表。每个条目在数据库中有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电子表格中,但它需要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
答案 0 :(得分:1)
您可以使用条件聚合,自联接或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;