简体   繁体   中英

I want a way to combine all these Oracle queries into one

 select 
 UNIT,
 NBR, 
 ODE,
 ANS,
 IT,
 UNIT,
 ESC,
DATE1,
DATE2,
CD,
CD2,
CD3,
TRANS
from Jblog
where UNIT = 'Alaska'
AND DATE1 > 0 and
DATE2 > 0
AND ODE = '67342'
AND NBR = '50952'



select
 UNIT,
 TRANS,
 ELER, 
 ELER_DATE,
 ELERDATE2, 
 TRANS
from JBLOG
where unit = 'ALASKA' 
AND ELER <> ' ' 
and ELERDATE > 0 and
ELERDATE2 > 0
and ELER = '5201'
 
select
 UNIT,
 TRANS,
 LNT,
 LNT_MIN, 
 LNT_MAX,
 LNT_D, 
 LNT_DATE1,
 LNT_DATE2,
 LNT_DATE3,
 LNT_AL,
 TRANS
from JBLOG
where UNIT = 'ALASKA'
AND LNT_DATE <> 0
AND LNT_DATE2 > 0 and
LNT_DATE3> 0
AND LNT_D = '0064'

 

I want to be able to combine all these queries and run them as one. The data is different so if I just straight up combine them and have one long where clause with a bunch of ands I won't get any results because the exclusion will make it not return any data. However, when I run them individually I get the desired result. I tried unions and it did not quite work out, does anyone have an solution? Thanks in advance

从表中以相同顺序选择所有列,然后使用并集将它们合并,从而产生所需的结果。

UNION should solve your problem, but note that UNION requires that the queries to be combined must return an equal sequence of attributes (concerning name and type).

So when combining above queries with UNION , each of the queries must select the same sequence of attributes; and if particular attributes make no sense in a particular query, you must still provide them, even if you chose to select a default value.

For example, the following query should work:

select a, b, NULL as c
  from table1
  where a>5
union
select a, NULL as b, c
  from table1
  where a<=5

whereas the following query doesn't:

select a, b
  from table1
  where a>5
union
select a, c
  from table1
  where a<=5

There has to be some kind of key to join by. Pick whatever fields make a unique item key and do a LEFT JOIN to a master list for each of those queries on those fields.

Since your queries filter out and won't necessarily have proper joins for everything, add another level to the query that picks everything without any filter so you can join everything to it:

select * 
from 
    (select UNIT /*or key whatever*/ from Jblog) all_units
LEFT JOIN
     (.....) a
ON a.unit = all_units.unit
LEFT JOIN
     (.....) b
ON b.unit = all_units.unit
LEFT JOIN
     (.....) c
ON c.unit = all_units.unit

where a, b, and c are your 3 queries you listed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM