既然取一条,当有多条时默认取ID最大应该。 select * from a where id in ( select max(id) from A where owedate in (select max(owedate) owedate from A where owedate is not null group by cellid) )
select *from a a1 where a1.id in (select top 1 id from a a2 where a2.cellid=a1.cellid order by owedate,id desc)
select a.* from A a, (select ID=max(ID),owedate=max(owedate) from A group by cellid) b where a.ID=b.ID
我看了一下,觉得大学结果都有问题。 比如 测试 create table ##temp ( id int identity(1,1), cellid int, type int, price int )insert ##temp select 12,1,131 insert ##temp select 12,3,123 insert ##temp select 13,2,145 insert ##temp select 12,2,122 insert ##temp select 13,1,111应得出 id cellid, type,price 3 13 2 145 2 12 3 123 但是用这个用例,上述答案都不正确
A表日期字段是可以为空的,当为空时,记录按id和owedate的降序排列取第一行。如果记录中日期不为空时,楼上的方法可以取出数据,但是如果存在两条以上日期为空记录的时候,就取不出来了。
比如
数据为 1, 101, 3000 2001-10-01
2, 101, 2500 2001-10-11
3, 102, 2800 2001-11-01
4, 101 2600 null
5, 103 2700 null
6, 102 2700 null
7, 103 2900 null
取出的数据应为
id cellid price owedate
2 101 2500 2001-10-11
3 102 2800 2001-11-01
7 103 2900 null
不好意思,刚才没说清楚!
select * from a where id in (
select max(id) from A where owedate in (select max(owedate) owedate from A where owedate is not null group by cellid)
)
(select ID=max(ID),owedate=max(owedate) from A group by cellid) b
where a.ID=b.ID
比如
测试 create table ##temp
(
id int identity(1,1),
cellid int,
type int,
price int
)insert ##temp select 12,1,131
insert ##temp select 12,3,123
insert ##temp select 13,2,145
insert ##temp select 12,2,122
insert ##temp select 13,1,111应得出
id cellid, type,price
3 13 2 145
2 12 3 123
但是用这个用例,上述答案都不正确