【问题标题】:Oracle how I can group by duplicate value of a column into an other columnOracle如何将一列的重复值分组到另一列
【发布时间】:2019-01-11 03:24:07
【问题描述】:

我有一个 oracle VIEW,它在一列中包含一些重复值

myView : 

---------------------------
ID  | col 1       | col 2  |
---------------------------
1   | P1          |V1
2   | P1          |V1
3   | P1          |V2
4   | P1          |V3
5   | P2          |t1
6   | P2          |t1
7   | P2          |t2

我想基于 myView 创建另一个视图,其中包含如下值:


ID  | col 1       | col 2  |col 3
---------------------------------------
1   | P1          |V1      |V1,V1,V2,V3
2   | P1          |V1      |V1,V1,V2,V3
3   | P1          |V2      |V1,V1,V2,V3
4   | P1          |V3      |V1,V1,V2,V3
5   | P2          |t1      |t1,t1,t2
6   | P2          |t1      |t1,t1,t2
7   | P2          |t2      |t1,t1,t2

提前感谢您的帮助

【问题讨论】:

    标签: sql oracle plsql sql-view


    【解决方案1】:

    你可以使用listagg()作为窗口函数:

    select t.*,
           listagg(col2, ',') within group (order by col1) over (partition by col1) as col3s
    from t;
    

    【讨论】:

    • 我们不需要添加partition by子句吗?如果必须忽略重复项怎么办
    • 此解决方案为我提供 col3 值,例如:每行的 V1,V1,V2,V3,t1,t1,t2
    • @ErrabiAyoub 。 . .它需要一个partition by。
    • 是的,分区解决了它的工作问题!谢谢男人
    【解决方案2】:
    select id, col1, col2, LISTAGG(col2, ',') WITHIN GROUP (ORDER BY col1) OVER (PARTITION BY col1) as col3 
    from myView;
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多