MySQL 自连接查询?

MySQL self join query?

我有一个 table 看起来像:

-------------------------------------
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 查询输出一个 table 像这样:

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 子句中的条件表达式选择对应于 AB 行的值。