一个常见得查询问题

yanggaoxing_007 2007-01-12 10:45:47
有一表A的字段有ID(identity(1,1)),cellid,price,owedate
数据为 1, 101, 3000 2001-10-01
2, 101, 2500 2001-10-11
3, 102, 2800 2001-11-01
.........
现在想根据cellid 进行分组查询,得出owedate日期最新的一条记录的SQL语句该怎么写?
比如得出结果为
id cellid price owedate
2 101 2500 2001-10- 11
3 102 2800 2001-11-01
........
不知说清楚了没有! thinks

...全文
253 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
yanggaoxing_007 2007-06-13
  • 打赏
  • 举报
回复
我看了一下,觉得大学结果都有问题。
比如
测试 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
但是用这个用例,上述答案都不正确
miller3000 2007-01-12
  • 打赏
  • 举报
回复
既然取一条,当有多条时默认取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)
)
akuzou 2007-01-12
  • 打赏
  • 举报
回复
如果某个cellid下有最大的日期有两个或两个以上,怎么取记录?
yanggaoxing_007 2007-01-12
  • 打赏
  • 举报
回复
谢谢楼上,正确,不过是这样的:
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
不好意思,刚才没说清楚!




caixia615 2007-01-12
  • 打赏
  • 举报
回复
ls正解
akuzou 2007-01-12
  • 打赏
  • 举报
回复
最容易理解的一种
select * from A where owedate in (select max(owedate) owedate from A group by cellid)
shiqiyuan 2007-01-12
  • 打赏
  • 举报
回复
select a.* from A a,
(select ID=max(ID),owedate=max(owedate) from A group by cellid) b
where a.ID=b.ID
hyc_music1981 2007-01-12
  • 打赏
  • 举报
回复
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)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧