简体   繁体   English

在Oracle 11g上将行转换为列

[英]Convert rows to columns on Oracle 11g

I have a table with two columns (Name and Gender). 我有一个包含两列(名称和性别)的表。 There are 4 records in my table. 我的表中有4条记录。

Name  Gender
A       Male
B       Female
C       Male
D       Female

I would like to write a SQL Query to convert the above data to below format. 我想编写一个SQL查询,将上述数据转换为以下格式。

Male      Female
A           B    
C           D

Another possibility similar to Tim's but only requires a single CTE: 与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';

By using a full outer join this also works if there is a different number of rows per gender. 如果每个性别的行数不同,则通过使用完全外部联接也可以使用。

Online example 在线示例

It may be as simple as that: 可能就这么简单:

SELECT m.Name Male, f.Name Female
FROM t m, t f
WHERE m.Gender = "Male" AND f.Gender = "Female";

But it doesn't make much sense, I hope you know what you're doing. 但这没有多大意义,我希望您知道自己在做什么。

Here is one option, using CTEs: 这是使用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;

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM