SQL:使用多个值进行分组,并避免该组中为null

时间:2018-09-22 01:06:46

标签: sql oracle

我有一个具有这样的值的表,在这里,我需要为每个Trans ID保留一行。我可以获取该记录的最少Trans数据

    Trans Date  Trans id    Name
12/1/2017 14:44 T1  
12/1/2017 16:44 T1          test
12/1/2017 16:44 T2  

需要这样的输出

Trans Date       Trans id   Name
12/1/2017 14:44     T1      test
12/1/2017 16:44     T2  

我尝试过这样的查询,但这给了我两行名称

select unique min(Trans Date), Trans id, Name from tabl1 group by Trans id, Name

但获得所有结果。请建议

2 个答案:

答案 0 :(得分:1)

我们可以使用row_numbermax分析函数来做到这一点。

还应在列Double Quotes中使用带有空格的列名,但应将其命名为case sensitive。检查表定义以获取正确的列名。

select "Trans id" ,"Trans Date",m_name as name
from 
(
select t.*, 
 row_number() over (partition by "Trans id" order by "Trans Date") as rn
 ,max(name) over (partition by "Trans id" order by "Trans Date") as m_name
from table1 t
)
where rn=1

答案 1 :(得分:0)

通常,Oracle中最有效的方法是使用keep

select trans_id, min(trans_date),
       min(name) keep (dense_rank first order by trans_date desc) as name
from tab1
group by trans_id;