0

Consider Table like this. I will call it Test

Id  A   B   C   D
1   1   1   8   25
2   1   2   5   35
3   1   3   2   75
4   2   2   2   45
5   3   2   5   26

Now I want rows with max 'Id' Grouped by 'A'

Id  A   B   C   D
3   1   3   2   75
4   2   2   2   45
5   3   2   5   26

-

--Work, but I do not want
SELECT  MAX(Id), A           FROM  Test GROUP BY A
--I want but do not work           
SELECT  MAX(Id), A, B, C, D  FROM  Test GROUP BY A 
--Work but I do not want         
SELECT  MAX(Id), A, B, C, D  FROM  Test GROUP BY A, B, C, D  
--Work and I want   
SELECT old.Id, old.A, new.B, new.C, new.D  
FROM(
   SELECT 
       MAX(Id) AS Id, A
   FROM 
       Test GROUP BY A
   )old
JOIN Test new
ON old.Id = new.Id

Is there a better way to write last query without join

1
  • 2
    tag the question with the dbms being used Jun 27, 2016 at 17:50

2 Answers 2

3

Most databases support window functions:

select * 
from (
    select *, row_number() over (partition by a order by id desc) rn
    from test
) t
where rn = 1
1

Most DBMS now support Common Table Expressions (CTE). You can use one.

;with maxa as (
select row_number() over(partition by a order by id desc) rn,
id,a,b,c,d from test
)
select id,a,b,c,d
from maxa
where rn=1
3
  • 1
    Why a CTE instead of the direct query?
    – Andrew
    Jun 27, 2016 at 17:59
  • OP wants max(id) with all columns unchanged. Aggregate functions with group by doesn't return what they want. Jun 27, 2016 at 18:02
  • How it change columns?
    – topolm
    Jun 28, 2016 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.