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

南笙酒味 提交于 2019-12-23 20:04:34

问题


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?


回答1:


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 |



回答2:


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


来源:https://stackoverflow.com/questions/13461902/sql-server-select-distinct-by-one-column-and-by-another-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!