34,588
社区成员
发帖
与我相关
我的任务
分享
select id,customerid,[datetime],[value] from
(select *,row_number() over(partition by customerid order by datetime desc,value desc) as rn from tb) p
where rn = 1
/*
id customerid datetime value
----------- ----------- ----------------------- -----------
2 1 2009-12-12 00:00:00.000 4
3 2 2009-12-14 00:00:00.000 2
(2 行受影响)
*/
select id,customerid,[datetime],[value] from
(select *,row_number() over(partition by customerid order by datetime,value desc) as rn from tb) p
where rn = 1
/*
id customerid datetime value
----------- ----------- ----------------------- -----------
2 1 2009-12-12 00:00:00.000 4
3 2 2009-12-13 00:00:00.000 1
(2 行受影响)
*/
----------------------------------------------------------------
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2009-12-23 15:09:12
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[customerid] int,[datetime] varchar(10),[value] int)
insert [tb]
select 1,1,'2009-12-12',3 union all
select 2,1,'2009-12-12',4 union all
select 3,2,'2009-12-13',1 union all
select 4,2,'2009-14-14',2
--------------开始查询--------------------------
select
*
from
tb t
where
not exists(select 1 from tb where customerid = t.customerid and (datetime > t.datetime or (datetime=t.datetime and id > t.id)))
----------------结果----------------------------
/* id customerid datetime value
----------- ----------- ---------- -----------
2 1 2009-12-12 4
4 2 2009-14-14 2
(2 行受影响)
*/
create table tb(id int, customerid int, [datetime] datetime, value int)
insert into tb values(1 , 1 , '2009-12-12' , 3 )
insert into tb values(2 , 1 , '2009-12-12' , 4 )
insert into tb values(3 , 2 , '2009-12-13' , 1 )
insert into tb values(4 , 2 , '2009-12-14' , 2 )
go
select t.* from tb t where not exists(select 1 from tb where customerid = t.customerid and (datetime > t.datetime or (datetime=t.datetime and id > t.id)))
drop table tb
/*
id customerid datetime value
----------- ----------- ------------------------------------------------------ -----------
2 1 2009-12-12 00:00:00.000 4
4 2 2009-12-14 00:00:00.000 2
(所影响的行数为 2 行)
*/
select
*
from
tb t
where
id=(select max(id) from tb where customerid=t.customerid and datetime=t.datetime)
select
*
from
tb t
where
id=(select max(id) from tb where customerid=a.customerid and datetime=t.datetime)
select * from 表 a where not exists
(
select 1 from 表 where customerid=a.customerid and datetime <a.datetime
)
select * from 表 t where not exists(select 1 from 表 where customerid=t.customerid and value<t.value)