SQL

时间:2019-04-16 13:38:11

标签: sql sql-server oracle select concatenation

我正在尝试编写一个Oracle或MS SQL脚本,该脚本输出的第一行包含A列中的单元格值,第二行包含A列与B列连接并用逗号分隔的单元格值, 第三行包含A,B和C列的单元格值,这些值由逗号连接并分隔。

假设以下SQL表:

|columnA |columnB|columnC |columnD |columnF |columnG |  
|--------|-------|--------|--------|--------|--------|
|  matty | lucy  |  james | mike   | tala   | mark   | 
|  jana  | steph |  alex  | mohd   | hani   | elie   |

输出为:

matty 
matty,lucy
matty,lucy,james
matty,lucy,james,mike 
matty,lucy,james,mike,tala
matty,lucy,james,mike,tala,mark
jana
jana,steph
jana,steph,alex
jana,steph,alex,mohd
jana,steph,alex,mohd,hani
jana,steph,alex,mohd,hani,elie

我应该如何编写SQL select语句?

3 个答案:

答案 0 :(得分:2)

您可以使用apply

select tt.*
from table t cross apply
     ( values (columnA, null, null, null, null, null),
              (columnA, columnB, null, null, null, null),
               . . . 
              (columnA, columnB, columnC, columnD, columnF, columnG)    
     ) tt(col1, col2, col3, col4, col5, col6);

如果要将所有数据合并到一个列中,请使用concat()

select tt.*
from table t cross apply
     ( values (columnA),
              (concat(columnA, ',', columnB)),
              (concat(columnA, ',', columnB, ',', columnC)),
              (concat(columnA, ',', columnB, ',', columnC, ',', columnD)),
              (concat(columnA, ',', columnB, ',', columnC, ',', columnD, ',', columnF)),
              (concat(columnA, ',', columnB, ',', columnC, ',', columnD, ',', columnF, ',', columnG))
     ) tt(cols);

答案 1 :(得分:1)

一种方法是取消数据透视并进行递归级联(Oracle解决方案):

--data 
with t(a, b, c, d, e, f) as (
    select 'matty', 'lucy',  'james', 'mike', 'tala', 'mark' from dual union all 
    select 'jana ', 'steph', 'alex',  'mohd', 'hani', 'elie' from dual )
-- end of data
select ltrim(sys_connect_by_path(name, ','), ',') path
  from (select rownum r1, a, b, c, d, e, f from t) 
        unpivot (name for r2 in (a as 1, b as 2, c as 3, d as 4, e as 5, f as 6))
  connect by prior r1 = r1 and r2 = prior r2 + 1
  start with r2 = 1

demo

答案 2 :(得分:1)

如果您想要在两个数据库中都可以使用的版本:

select colA
from t
union all
select concat(Col1, concat(',', colB))
from t
union all
select concat(concat(Col1, concat(',', colB)), concat(',', colC))
from t
union all
. . .