我试图在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
谢谢 (对不起我的英文..)
答案 0 :(得分:0)
如果您只是想忽略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
/
[编辑] 回应评论:
如果你想保持工会,那很好,工会和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标准;) 相同的逻辑可以应用于我上面使用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
/
答案 1 :(得分:0)
在“' WHERE'中改变您的条件会是这种情况。来自
的条款WHERE NAME = 'JOAO' AND FLAG = '0'
到
WHERE NAME = 'JOAO' AND FLAG IN('0','1')
因此,您的选择会显示所有带有' 0'或者' 1'列' FLAG'。
的值答案 2 :(得分:0)
您可以使用COALESCE()。 http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617/ms190349.aspx
此Query应适用于每个名称,并且应该合并其他行。
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;