[英]Union null in Oracle
我正在嘗試在oracle中合並2個查詢,這些行具有相同的值,但需要一個字段。
例如:
SELECT NAME, AGE, EMAIL, DATE FROM table_a WHERE NAME = 'JOAO' AND FLAG = '0'
UNION
SELECT NAME, AGE, EMAIL, DATE FROM table_a WHERE NAME = 'JOAO' AND FLAG = '1'
結果:
NAME AGE EMAIL DATE
JOAO 23 a@a.com 20150414
JOAO 23 a@a.com null
我如何將這些行分組? 我正在尋找可以給我類似結果的東西:
NAME AGE EMAIL DATE
JOAO 23 a@a.com 20150414
謝謝你(抱歉我的英語..)
如果您只是想忽略NULL值:
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG in ( '0', '1' )
and date is not null
/
或者如果您想保留空值,但要遵循可用的非空值:
with w_data as (
SELECT NAME, AGE, EMAIL, DATE ,
row_number() over ( partition by name
order by date desc nulls last ) rnum
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG in ( '0', '1' )
)
select name, age, email, date
from w_data
where rnum = 1
/
[edit]回應評論:
如果您想保留聯合,那很好,聯合和OR大多可以互換(在這種情況下):
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG = '0'
and date is not null
union
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG = '1'
and date is not null
/
甚至:
select * from (
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG = '0'
union
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG = '1'
)
where date is not null
/
如果您只想將NULL條件放在1個位置;)相同的邏輯可以應用於我上面使用row_number()分析編寫的第二個查詢...
with w_data as (
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG = '0'
union
SELECT NAME, AGE, EMAIL, DATE
FROM table_a
WHERE NAME = 'JOAO'
AND FLAG = '1'
),
w_sub as (
select name, age, email, date,
row_number() over ( partition by name
order by date desc nulls last ) rnum
from w_data
)
select name, age, email, date
from w_sub
where rnum = 1
/
在這種情況下,您可以在“ WHERE”子句中更改您的條件
WHERE NAME = 'JOAO' AND FLAG = '0'
至
WHERE NAME = 'JOAO' AND FLAG IN('0','1')
因此,您的選擇將在“ FLAG”列中顯示所有值為“ 0”或“ 1”的寄存器。
您可以使用COALESCE()。 http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617/ms190349.aspx
該查詢應適用於每個名稱,並應合並其他行。
SELECT
NAME1 AS NAME,
COALESCE(AGE1, AGE2) AS AGE,
COALESCE(EMAIL1, EMAIL2) AS EMAIL,
COALESCE(DATE1, DATE2) AS DATE
FROM(
SELECT
t1.NAME AS NAME1,
t1.AGE AS AGE1,
t1.EMAIL AS EMAIL1,
t1.DATE AS DATE1,
t2.NAME AS NAME2,
t2.AGE AS AGE2,
t2.EMAIL AS EMAIL2,
t2.DATE AS DATE2
FROM table_a AS t1
INNER JOIN table_a AS t2
ON t2.FLAG = 1 AND t1.FLAG = 0 AND t1.NAME = t2.NAME
) AS t3;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.