我有一个看起来像这样的表:
-------------------------------------
col0 | col1 | col2 | .......| col10 |
-------------------------------------
1 | A | 2.5 | .......| 4.5 |
-------------------------------------
2 | A | 3.5 | .......| 5.5 |
-------------------------------------
3 | A | 4.5 | .......| 6.5 |
-------------------------------------
1 | B | 2.5 | .......| 4.5 |
-------------------------------------
2 | B | 3.5 | .......| 5.5 |
-------------------------------------
3 | B | 4.5 | .......| 6.5 |
-------------------------------------
1 | C | 2.5 | .......| 4.5 |
-------------------------------------
2 | C | 3.5 | .......| 5.5 |
-------------------------------------
我想运行一个SQL查询,输出如下所示的表:
col0 | A | B |
------------------
1 | 2.5 | 2.5 |
------------------
2 | 3.5 | 3.5 |
------------------
3 | 4.5 | 4.5 |
这是我尝试过的:
select table_a.col0,
table_a.col2 as "A" where table_a.col1="A",
table_b.col2 as "B" where table_b.col1="B"
from table as table_a inner join table as table_b
on table_a.col0=table_b.col0
和
select table_a.col0,
table_a.col2 as "A" where table_a.col1="A",
table_b.col2 as "B"
from table as table_a inner join table as table_b
on table_a.col0=table_b.col0 where table_b.col1="B";
为了解决语法错误,我尝试了很多不同的查询,但仍然没有运气。 SQL新手,请提供帮助。
您可以进行条件聚合来旋转数据集:
select
col0,
max(case when col1 = 'A' then col2 end) A,
max(case when col1 = 'B' then col2 end) B
from mytable
where col1 in ('A', 'B')
group by col0
查询将col0
中具有相同值的行分组在一起;然后,select
子句中的条件表达式将选择与A
和B
行相对应的值。