0

i have table:

╔════╤════════════╗
║ id │ date       ║
╠════╪════════════╣
║ 1  │ 2001-08-01 ║
╟────┼────────────╢
║ 1  │ 2001-09-02 ║
╟────┼────────────╢
║ 1  │ 2001-09-02 ║
╟────┼────────────╢
║ 1  │ 2001-09-01 ║
╟────┼────────────╢
║ 2  │ 2000-01-01 ║
╟────┼────────────╢
║ 3  │ 2000-09-01 ║
╚════╧════════════╝

and want to receive a max date using code:

SELECT tt.*
FROM data tt
inner join(
SELECT id, max(data) as lastDate
FROM data
GROUP BY id) groupedtt
ON tt.id = groupedtt.id AND tt.data = groupedtt.lastDate

but via this code i get duplicate values like

╔════╤════════════╗
║ id │ date       ║
╠════╪════════════╣
║ 1  │ 2001-09-02 ║
╟────┼────────────╢
║ 1  │ 2001-09-02 ║
╟────┼────────────╢
║ 2  │ 2000-01-01 ║
╟────┼────────────╢
║ 3  │ 2000-09-01 ║
╚════╧════════════╝

what should i change to get table without dupliates like this:

╔════╤════════════╗
║ id │ date       ║
╠════╪════════════╣
║ 1  │ 2001-09-02 ║
╟────┼────────────╢
║ 2  │ 2000-01-01 ║
╟────┼────────────╢
║ 3  │ 2000-09-01 ║
╚════╧════════════╝

i'm using ms sql server

4
  • 2
    Simply SELECT DISTINCT. Commented Apr 26, 2018 at 20:36
  • 1
    or GROUP BY id int the main query Commented Apr 26, 2018 at 20:38
  • @jarlh but why use JOIN in the first place? Commented Apr 26, 2018 at 20:43
  • No @jarlh that won't work here. The OP needs to get the maximum date for each id. Commented Apr 26, 2018 at 20:51

2 Answers 2

3

Just use the query you are using to join your original table:

SELECT id, max(date) as [date]
FROM data
GROUP BY id;
Sign up to request clarification or add additional context in comments.

Comments

1

Use row_number() if you want the whole row:

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

I'm guessing there are other fields you want from the row, because your subquery does exactly what you specify that you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.