Oracle10g SQL 枢轴
我有一个名为 TABLE 的表,例如,如下所示:
ID | email
--------------
1 | [email protected]
1 | [email protected]
2 | [email protected]
3 | [email protected]
3 | [email protected]
我想返回类似
ID | email1 | email2
--------------------
1 | [email protected]| [email protected]
2 | [email protected]|
3 | [email protected]| [email protected]
我想知道如何使用透视来帮助我摆脱重复的 ID 行并为其他电子邮件添加额外列的内容。感谢您的帮助。
SELECT id, email1, email2, email3
FROM (
SELECT id,
email,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY email) AS emailRank
FROM TABLE
)
pivot( max(email) FOR emailRank IN (1 as email1, 2 as email2, 3 as email3));
编辑:由于海滩的回答而修复了上面的问题
I have a table named TABLE for example looking like:
ID | email
--------------
1 | [email protected]
1 | [email protected]
2 | [email protected]
3 | [email protected]
3 | [email protected]
and I would like to return something like
ID | email1 | email2
--------------------
1 | [email protected]| [email protected]
2 | [email protected]|
3 | [email protected]| [email protected]
I was wondering how I could use pivoting to help me get rid of duplicate ID rows and just add an extra column for their other emails. Thanks for the help.
SELECT id, email1, email2, email3
FROM (
SELECT id,
email,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY email) AS emailRank
FROM TABLE
)
pivot( max(email) FOR emailRank IN (1 as email1, 2 as email2, 3 as email3));
Edit: fixed above thanks to beach's answer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我更喜欢使用带有 CASE 表达式的 GROUP BY 解决方案。
原始数据透视示例有类型但缺少“)”。请尝试以下操作以使枢轴正常工作:
I prefer using the GROUP BY solution with CASE expression.
Original Pivot example had type and missing ")". Try the following to get pivot working:
您可以使用过程或 group by rownum 和解码的组合。就我个人而言,我发现该程序方法更干净。
请参阅:http://asktom.oracle.com/pls/apex/f?p=100:11:0::NO::P11_QUESTION_ID:15151874723724
You can use a procedure or a combination of group by rownum and decode. Personally, I find the procedure approach cleaner.
See: http://asktom.oracle.com/pls/apex/f?p=100:11:0::NO::P11_QUESTION_ID:15151874723724