zoukankan      html  css  js  c++  java
  • SQL 列转行的实现

    --列转行,逗号拼接指定列的值

    SQL Server中写法:
    SELECT STUFF(( SELECT  ',' + Field1 from TableA FOR XML PATH('')), 1, 1, '')


    Oracle中写法:

    方法一:wmsys.wm_concat
    select wmsys.wm_concat(Field1) from TableA

    方法二:LISTAGG()

    2.1、LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX)

    用法就像聚合函数一样,通过Group by语句,把每个Group的一个字段,拼接起来

     1 with temp as(
     2   select 'China' nation,'Beijing' city from dual union
     3   select 'China' nation,'Shanghai' city from dual union
     4   select 'China' nation,'Guangzhou' city from dual union
     5   select 'USA' nation,'New York' city from dual union
     6   select 'USA' nation,'Bostom' city from dual
     7 )
     8 select nation,listagg(city,',') within group(order by city)
     9 from temp
    10 group by nation;

    2.2、over(partition by XXX)

    在不使用Group by语句时候,使用LISTAGG函数(当作SUM()函数来使用)

    1 with temp as(
    2   select 'China' nation,'Beijing' city from dual union
    3   select 'China' nation,'Shanghai' city from dual union
    4   select 'China' nation,'Guangzhou' city from dual union
    5   select 'USA' nation,'New York' city from dual union
    6   select 'USA' nation,'Bostom' city from dual
    7 )
    8 select nation,city,listagg(city,',') within group(order by city) over(partition by nation) rank
    9 from temp;
  • 相关阅读:
    CF431E Chemistry Experiment
    BZOJ 4173: 数学
    BZOJ 2426: [HAOI2010]工厂选址
    BZOJ 2580: [Usaco2012 Jan]Video Game
    BZOJ 4237: 稻草人
    BZOJ 2434: [Noi2011]阿狸的打字机
    BZOJ 3881: [Coci2015]Divljak
    BZOJ 2754: [SCOI2012]喵星球上的点名
    BZOJ 1009: [HNOI2008]GT考试
    BZOJ 3731: Gty的超级妹子树
  • 原文地址:https://www.cnblogs.com/AnneHan/p/6224980.html
Copyright © 2011-2022 走看看