sql查询问题—极具挑战性

小__猪 2003-08-29 07:46:26
有一个简单的表如下:有三个int型字段
ymdhm stcdt water
1 1 15
2 1 15
3 1 16
4 1 16
1 2 17
2 2 18
3 2 18
4 2 17

希望提供一句sql查询语句,能够求得每个stcdt数值下(1,2)的water为最大值时的任意一条记录。即结果如下:
ymdhm stcdt water
3(也可以是4) 1 16(stcdt为1时的最大值)
2(也可以是3) 2 18(stcdt为2时的最大值)


这是别人问我,我说2分钟搞定,结果2个小时也没有搞定,希望有高手能帮小弟一把。
...全文
41 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
小__猪 2003-08-30
  • 打赏
  • 举报
回复
小狮子兄的查询语句好像得出的结果不对,如果是我理解错了,在此深感抱歉。
小__猪 2003-08-30
  • 打赏
  • 举报
回复
非常感谢各位大侠的鼎力相助,区区几十分,还望笑纳。
zjcxc 元老 2003-08-29
  • 打赏
  • 举报
回复
错了,应该是:
select ymdhm=max(a.ymdhm),b.stcdt,b.water
from # a,(select stcdt,water=max(water) from # group by stcdt) b
where a.stcdt=b.stcdt and a.water=b.water
group by b.stcdt,b.water

或:
select ymdhm=min(a.ymdhm),b.stcdt,b.water
from # a,(select stcdt,water=max(water) from # group by stcdt) b
where a.stcdt=b.stcdt and a.water=b.water
group by b.stcdt,b.water
zjcxc 元老 2003-08-29
  • 打赏
  • 举报
回复
select ymdhm=max(ymdhm),stcdt,water=max(water)
from 表名 group by stcdt
CSDNM 2003-08-29
  • 打赏
  • 举报
回复
select * from tablename a
where water=(select max(water) from tablename where stcdt=a.stcdt)
and ymdhm=(select max(ymdhm) from tablename where stcdt=a.stcdt and water=a.water)

txlicenhe 2003-08-29
  • 打赏
  • 举报
回复
Try:
Select max(a.ymdhm),b.stcdt,b.water from table a
join
(Select stcdt,max(water) as water from table group by stcdt) b
on a.stcdt = b.stcdt and a.water = b.water
group by b.stcdt,b.water

pengdali 2003-08-29
  • 打赏
  • 举报
回复
测试:

create table # (ymdhm int, stcdt int, water int)
insert # values(1, 1 , 15)
insert # values(2 , 1 , 15)
insert # values(3 , 1 , 16)
insert # values(4 , 1 , 16)
insert # values(1 , 2 , 17)
insert # values(2 , 2 , 18)
insert # values(3 , 2 , 18)
insert # values(4 , 2, 17)


select * from # a where ymdhm=(select top 1 ymdhm from # where stcdt=a.stcdt order by water desc)

go
drop table #
pengdali 2003-08-29
  • 打赏
  • 举报
回复
select * from 你的表 a where ymdhm=(select top 1 ymdhm from 你的表 where stcdt=a.stcdt order by water desc)
lionstar 2003-08-29
  • 打赏
  • 举报
回复
select ymdhm,maxwater,stcdt from tablename as tb1,
(select max(tb2.water) as maxwater, tb2.stcdt as tb2stcdt
from tablename as tb2
group by tb2.stcdt) as stmt
where tb1.stcdt=stmt.tb2stcdt
小__猪 2003-08-29
  • 打赏
  • 举报
回复
补充一下,该表的主键为ymdhm和stcdt.即每行记录中这两个字段不重复。

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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