首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将列转换为具有相同数据的行( SQL )

将列转换为具有相同数据的行( SQL )
EN

Stack Overflow用户
提问于 2015-08-11 07:33:08
回答 2查看 97关注 0票数 0

我有一个名为t1的表,它有6列。现在,我需要创建一个基于列的报告,其中包含C、D、E列中的每个数据,作为表t2这样的单独行。如何在oracle中为相同的SQL查询编写SQL查询。

表T1 (当前表值)

代码语言:javascript
复制
A   B   C   D       E       F
1   AE  21  S-1     F-A     POST
1   AE  31  NULL    NULL    POST
1   AE  41  NULL    NULL    PRE
1   AE  51  S-2     R-A     PRE

表T2 (例外结果)

代码语言:javascript
复制
A   B   C       D       E       F
1   AE  21      NULL    NULL    POST
1   AE  NULL    S-1     NULL    POST
1   AE  NULL    NULL    F-A     POST
1   AE  31      NULL    NULL    POST
1   AE  41      NULL    NULL    PRE
1   AE  NULL    S-2     NULL    PRE
1   AE  NULL    NULL    R-A     PRE
1   AE  51      NULL    NULL    PRE
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-08-11 07:44:01

使用UNION查询分别获取每个字段的值。包括您的键值(a,b),然后每个非空字段单独。下面是一个例子:

代码语言:javascript
复制
select a,b, c, null d, null e, f from t1 where c is not null
union
select a,b, null c, d, null e, f from t1 where d is not null
union
select a,b, null c, null d, e, f from t1 where e is not null
票数 2
EN

Stack Overflow用户

发布于 2015-08-11 07:52:07

我做了另一个表t0,并这样使用它:

代码语言:javascript
复制
with t1 as 
        (select 1 A, 'AE' B, 21 C, 'S-1' D, 'F-A' E, 'POST' F from dual union all
         select 1,   'AE',   31,   null ,   null,    'POST' from dual union all
         select 1,   'AE',   41,   null ,   null,    'PRE' from dual union all
         select 1,   'AE',   51,   'S-1' ,  'R-A',   'PRE' from dual),
t0 as 
        (select 'C' x from dual union all
         select 'D' from dual union all
         select 'E' from dual)
select a,
       b,
       case when t0.x = 'C' then c end c,
       case when t0.x = 'D' then d end d,
       case when t0.x = 'E' then e end e,
       f
  from t1,t0 
 where not (    case when t0.x = 'C' then c end is null
            and case when t0.x = 'D' then d end is null
            and case when t0.x = 'E' then e end is null)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31935787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档