我有一个包含两列(名称和性别)的表。我的表中有4条记录。
Name Gender
A Male
B Female
C Male
D Female
我想编写一个SQL查询,将上述数据转换为以下格式。
Male Female
A B
C D
答案 0 :(得分:2)
另一种与Tim相似的可能性,但只需要一个CTE:
with numbered as (
select name, gender, row_number() over (partition by gender order by name) as rn
from the_table
)
select f.name as "Female", m.name as "Male"
from numbered f
full outer join numbered m on m.rn = f.rn and m.gender = 'Male'
where f.gender = 'Female';
如果每个性别的行数不同,则使用完全外部联接也可以。
答案 1 :(得分:0)
可能就这么简单
SELECT m.Name Male, f.Name Female
FROM t m, t f
WHERE m.Gender = "Male" AND f.Gender = "Female";
但这没有多大意义,我希望你知道自己在做什么。
答案 2 :(得分:0)
这是使用CTE的一种选择:
WITH male AS (
SELECT Name, ROW_NUMBER() OVER (ORDER BY Name) rn
FROM yourTable
WHERE Gender = 'Male'
),
female AS (
SELECT Name, ROW_NUMBER() OVER (ORDER BY Name) rn
FROM yourTable
WHERE Gender = 'Female'
)
SELECT m.Name AS Male, f.Name AS Female
FROM male m
INNER JOIN female f
ON m.rn = f.rn;