【问题标题】:How do you combine query results from different rows into one?如何将来自不同行的查询结果合并为一个?
【发布时间】:2023-02-04 01:58:57
【问题描述】:

我的原始查询:

SELECT desc, start_date
from foo.bar
WHERE desc LIKE 'Fall%' AND desc NOT LIKE '%Med%'
UNION
SELECT desc, end_date
from foo.bar
WHERE desc LIKE 'Spring%' AND desc NOT LIKE '%Med%'
ORDER BY start_date;

通过上面的查询,我(大致)得到了我正在寻找的数据集。我现在需要获取该数据并按顺序合并一次两个的结果,然后产生如下结果:

DESC START_DATE END_DATE
Fall 1971 - Spring 1972 15-AUG-71 15-MAY-72
Fall 1971 - Spring 1972 15-AUG-72 15-MAY-73

其中 DESC 是 DESC 表格第 1 行和第 2 行的串联,START_DATE 是第 1 行的日期,END_DATE 是第 2 行的日期。整个数据集遵循相同的模式。

非常感谢任何能产生我需要的结果的查询帮助。不确定我是否走在正确的道路上,或者最初的查询是否是错误的。

如上所述,我尝试了提供的查询,它为我提供了所需的数据。但是,我一直未能找到将其格式化为所需输出的方法。还应该注意的是,我在 Oracle 数据库上运行它。

【问题讨论】:

    标签: sql oracle oracle19c


    【解决方案1】:

    代替 union,将这些查询中的每一个用作 CTE(稍作修改 - 包括您稍后将在 JOIN 中使用的行号):

    样本数据:

    SQL> with test (description, datum) as
      2    (select 'Fall 1971'  , date '1971-08-15' from dual union all
      3     select 'Spring 1972', date '1972-05-15' from dual union all
      4     select 'Fall 1972'  , date '1972-08-15' from dual union all
      5     select 'Spring 1973', date '1973-05-15' from dual union all
      6     select 'Fall 1973'  , date '1973-08-15' from dual union all
      7     select 'Spring 1974', date '1974-05-15' from dual union all
      8     select 'Fall 1974'  , date '1974-08-15' from dual union all
      9     select 'Spring 1975', date '1975-05-15' from dual
     10    ),
    

    查询从这里开始:t_startt_end 代表您当前的查询

     11  t_start as
     12    (select description, datum,
     13       row_number() Over (order by datum) rn
     14     from test
     15     where description like 'Fall%' and description not like '%Med%'
     16    ),
     17  t_end as
     18    (select description, datum,
     19       row_number() Over (order by datum) rn
     20     from test
     21     where description like 'Spring%' and description not like '%Med%'
     22    )
    

    最后:

     23  select s.description ||' - '|| e.description as description,
     24    s.datum start_date,
     25    e.datum end_date
     26  from t_start s join t_end e on s.rn = e.rn
     27  order by s.rn;
    
    DESCRIPTION               START_DAT END_DATE
    ------------------------- --------- ---------
    Fall 1971 - Spring 1972   15-AUG-71 15-MAY-72
    Fall 1972 - Spring 1973   15-AUG-72 15-MAY-73
    Fall 1973 - Spring 1974   15-AUG-73 15-MAY-74
    Fall 1974 - Spring 1975   15-AUG-74 15-MAY-75
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多