这是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查询?
答案 0 :(得分: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
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
或者你可以加入桌子:
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
所有查询都会产生相同的结果:
| 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 |
答案 1 :(得分: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