查询:按一列分组并选择antoher列

时间:2017-06-26 13:01:16

标签: sql oracle

我的查询有问题

我应该创建一个采用最后状态的查询(所以检查日期),为一个被调用的列mat_calc分组。

mat_calc | STATE | DATE

1 | NEW | 25/03/2016

1 | DONE |25/01/2016

2 |PROC |25/04/2016

2 |PROC |25/07/2016

2 |DONE |25/09/2016

3 |NEW |25/01/2016

3 |PROC |25/06/2016

3 |DONE |25/02/2016

3 |OK |25/12/2016

4 |OK |25/03/2016

所以我应该回复:

mat_cal及其状态

1 | NEW

2 | DONE

3 | OK

4 | OK

我的查询是

select mat_cal AS mat_cal , STATO AS STATO, MAX(DATA) AS DATA
from CALC
group by mat_cal ;

它给我带来组ID的麻烦,因为它看起来我不使用它。

我该怎么办?感谢

抱歉,我无法使用堆栈溢出来执行表格

3 个答案:

答案 0 :(得分:1)

使用row_number()

select c.*
from (select c.*,
             row_number() over (partition by mat_cal order by data desc) as seqnum
      from calc c
     ) c
where seqnum = 1;

答案 1 :(得分:0)

当您使用Group By子句时,您需要对所选的所有列执行此操作。如果你不这样做,你将获得ORA-00979例外。

尝试将STATO列添加到Group By

   select mat_cal AS mat_cal , STATO AS STATO, MAX(DATA) AS DATA
    from CALC
    group by mat_cal, STATO ;

答案 2 :(得分:0)

您可以尝试以下方法:

--creating the data you publishied
 with calc (mat_cal,STATO,date)
 as 
 (
 select '1' as mat_cal,'NEW' as STATO,'25/03/2016' as date
 union
 select '1','DONE','25/01/2016'
 union
 select '2','PROC','25/04/2016'
 union
 select '2','PROC','25/07/2016'
 union 
 select '2','DONE','25/09/2016'
 union 
 select '3','NEW','25/01/2016'
 union 
 select '3','PROC','25/06/2016'
 union 
 select '3','DONE','25/02/2016'
 union 
 select '3','OK','25/12/2016'
 union 
 select '4','OK','25/03/2016')


--the query to solve the problem 
select mat_cal , STATO ,date
from CALC as c
where c.date = (select max(date) from calc as c2 where c.mat_cal = c2.mat_cal group by c2.mat_cal)