3

这是一个 SQL Server 表的数据

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

user_id我还需要得到不同的值order by id asc,但只有一个user_id具有最高 start_date

我需要以下输出:

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

请帮忙!

什么是 SQL 查询?

4

2 回答 2

3

您可以row_number()在子查询中使用或使用 CTE。

子查询版本:

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

请参阅带有演示的 SQL Fiddle

CTE 版本:

;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

请参阅带有演示的 SQL Fiddle

或者您可以将表连接到自身:

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

请参阅带有演示的 SQL Fiddle

所有查询都将产生相同的结果:

| 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 |
于 2012-11-19T20:48:17.067 回答
0

不是最好的和未经测试的:

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
于 2012-11-19T20:53:36.577 回答