Oracle10g SQL 枢轴

Oracle10g SQL pivot(Oracle10g SQL 枢轴)
本文介绍了Oracle10g SQL 枢轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 TABLE 的表,例如:

I have a table named TABLE for example looking like:

ID  | email
--------------
1   |  a@a.com 
1   |  b@b.com
2   |  c@c.com
3   |  d@d.com
3   |  e@e.com

我想返回类似的东西

ID | email1 | email2
--------------------
1  | a@a.com| b@b.com
2  | c@c.com|
3  | d@d.com| e@e.com

我想知道如何使用数据透视来帮助我摆脱重复的 ID 行,并为他们的其他电子邮件添加一个额外的列.感谢您的帮助.

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));

由于海滩的回答,上面已修复

fixed above thanks to beach's answer

推荐答案

我更喜欢使用带有 CASE 表达式的 GROUP BY 解决方案.

I prefer using the GROUP BY solution with CASE expression.

SELECT 
    id,
    MAX(CASE WHEN emailRank = 1 THEN email END) AS [1],
    MAX(CASE WHEN emailRank = 2 THEN email END) AS [2],
    MAX(CASE WHEN emailRank = 3 THEN email END) AS [3],
    MAX(CASE WHEN emailRank = 4 THEN email END) AS [4]
FROM (
    SELECT
        id, 
        email, 
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY email) AS emailRank
    FROM TABLE
)
GROUP BY id;

原始 Pivot 示例具有类型且缺少)".尝试以下操作以使枢轴工作:

Original Pivot example had type and missing ")". Try the following to get pivot working:

pivot( max(email) FOR emailRank IN (1,2,3));

这篇关于Oracle10g SQL 枢轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)