[英]Transposing rows to columns in oracle
I'm trying to transpose rows in an Oracle statement into columns.我正在尝试将 Oracle 语句中的行转换为列。 I've been trying to read up and I guess what I need is a PIVOT.我一直在努力阅读,我想我需要的是一个 PIVOT。 But from countless examples I'm not able to figure out what I need to write.但是从无数的例子中我无法弄清楚我需要写什么。
I have two tables, one with persons and with with relations.我有两张桌子,一张是人和关系。 Parents have one reference each to a child, so two parents will be two rows in the relation table.父母对每个孩子都有一个引用,因此两个父母将是关系表中的两行。
Person table:人表:
id name
1 John Doe
2 Jane Doe
3 Johnny Doe
Relation table:关系表:
person_1_id person_2_id
1 3
2 3
So If I run the following SQL:因此,如果我运行以下 SQL:
SELECT child.id AS child_id, r.person_1_id AS parent_id
FROM person child
JOIN relation r ON r.person_2_id = child.id;
I get the following output:我得到以下输出:
child_id parent_id
3 1
3 2
How would I go about getting the output as:我将如何获得输出为:
child_id parent_1_id parent_2_id
3 1 2
I'm running Oracle 12c.我正在运行 Oracle 12c。
You can achieve the desired result using conditional aggregation as follows:您可以使用条件聚合实现所需的结果,如下所示:
SELECT
CHILD_ID,
MAX(CASE WHEN RN = 1 THEN PARENT_ID END) AS PARENT_1_ID,
MAX(CASE WHEN RN = 2 THEN PARENT_ID END) AS PARENT_2_ID
FROM
( SELECT
CHILD.ID AS CHILD_ID,
R.PERSON_1_ID AS PARENT_ID,
ROW_NUMBER() OVER(PARTITION BY CHILD.ID ORDER BY R.PERSON_1_ID) AS RN
FROM
PERSON CHILD
JOIN RELATION R ON R.PERSON_2_ID = CHILD.ID
)
GROUP BY CHILD_ID;
You can just use aggregation:您可以只使用聚合:
SELECT child.id AS child_id,
MIN(r.person_1_id) AS parent_id_1,
NULLIF(MAX(r.person_1_id), MIN(r.person_1_id) AS parent_id_2
FROM person child JOIN
relation r
ON r.person_2_id = child.id
GROUP BY child.id;
Subqueries do not seem to be necessary for this.为此似乎不需要子查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.