Dobrica Milentijevic
Dobrica Milentijevic

Reputation: 31

SQL Server : select distinct by one column and by another column value

This is a SQL Server table's data

id   user_id     start_date   status_id    payment_id
======================================================
2      4         20-nov-11         1          5
3      5         23-nov-11         1         245
4      5         25-nov-11         1         128
5      6         20-nov-11         1         223
6      6         25-nov-11         2         542
7      4         29-nov-11         2         123
8      4         05-jan-12         2         875

I need to get distinct values by user_id also order by id asc, but only one user_id with highest start_date

I need the following output:

id   user_id     start_date   status_id    payment_id
======================================================
8      4         05-jan-12         2         875
4      5         25-nov-11         1         128
6      6         25-nov-11         2         542

Please help!

What is SQL query for this?

Upvotes: 3

Views: 5424

Answers (2)

alzaimar
alzaimar

Reputation: 4622

Not the best and untested:

select *
  from ServersTable 
  join (
    select User_Id, max(Id) as ID
      from ServersTable x
     where x.start_date = (
          select max(start_date)
            from ServersTable y
           where y.UserID = x.UserId
           )
     group by User_Id) s on ServersTable.Id = s.Id

Upvotes: 0

Taryn
Taryn

Reputation: 247650

You can use row_number() in either a sub-query or using CTE.

Subquery Version:

select id, user_id, start_date, status_id, payment_id
from
(
  select id, user_id, start_date, status_id, payment_id, 
    row_number() over(partition by user_id order by start_date desc) rn
  from yourtable
) src
where rn = 1

See SQL Fiddle with Demo

CTE Version:

;with cte as
(
  select id, user_id, start_date, status_id, payment_id, 
    row_number() over(partition by user_id order by start_date desc) rn
  from yourtable
)
select id, user_id, start_date, status_id, payment_id
from cte
where rn = 1

See SQL Fiddle with Demo

Or you can join the table to itself:

select t1.id, 
  t1.user_id, 
  t1.start_date, 
  t1.status_id, 
  t1.payment_id
from yourtable t1
inner join 
(
  select user_id, max(start_date) start_date
  from yourtable
  group by user_id
) t2
  on t1.user_id = t2.user_id
  and t1.start_date = t2.start_date

See SQL Fiddle with Demo

All of the queries will produce the same result:

| ID | USER_ID |                      START_DATE | STATUS_ID | PAYMENT_ID |
---------------------------------------------------------------------------
|  8 |       4 |  January, 05 2012 00:00:00+0000 |         2 |        875 |
|  4 |       5 | November, 25 2011 00:00:00+0000 |         1 |        128 |
|  6 |       6 | November, 25 2011 00:00:00+0000 |         2 |        542 |

Upvotes: 4

Related Questions