求达人一句sql语句 谢谢

莫鸣 2012-12-12 09:25:42
表结构大概是这样子的
zh name flag sd zj
1 zhang 1 23 26
1 zhang 2 26 33
1 zhang 3 33 36
.
.
2 li 1 56 89
2 li 2 89 103
2 li 3 103 106
2 li 4 106 108
.
.
.
3 wang 1 225 228
3 wang 2 228 230
....

具体是这样子的。flag 字段在增 , 然后求 flag 最大的那列 sd 和zj的值然后把 其他的列删除了。
比如上面的要求的结果是:
zh name flag sd zj
1 zhang 3 33 36
2 li 4 106 108
3 wang 2 228 230


请问这句sql如何写?
...全文
135 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
我的tcl 2012-12-12
  • 打赏
  • 举报
回复
select zh,name,flag,sd,zj,row_number() over(partition by zh,name order by flag desc) as rn from tb1from 
xiaosa_21 2012-12-12
  • 打赏
  • 举报
回复

create table tb1 
(
zh int not null,
name nvarchar(10),
flag int not null,
sd int,
zj int
)

insert into tb1
select 1,'zhang',1,23,26
union all
select 1,'zhang',2,26,33
union all
select 1,'zhang',3,33,36
union all
select 2,'li',1,56,89
union all
select 2,'li',2,89,103
union all
select 2,'li',3,103,106
union all
select 2,'li',4,106,108
union all
select 3,'wang',1,225,228
union all
select 3,'wang',2,228,230

select zh,name,flag,sd,zj,sd+zj as summ from (
select zh,name,flag,sd,zj,row_number() over(partition by zh order by flag desc) as rn from tb1) a
where rn=1
qqqqqqqq_2013 2012-12-12
  • 打赏
  • 举报
回复
或者这样

 select * from Table a where not exists(select 1 from Table where zh=a.zh and flag>a.flag) 

qqqqqqqq_2013 2012-12-12
  • 打赏
  • 举报
回复
每行应该都有一个唯一的id吧?

select * from Table where id in (select id from Table where flag in (select max(flag) from Table group by zh))
希望对楼主有所启发
xuam 2012-12-12
  • 打赏
  • 举报
回复
select * from TB where not exists(select from TB a where TB.ID =a.id and TB.flag <a.flag)
Liu_cy88 2012-12-12
  • 打赏
  • 举报
回复
select * from Table t where flag = (select max(flag) from Table ts where t.zh = ts.zh)
快溜 2012-12-12
  • 打赏
  • 举报
回复
delete a from tb a where exists(select 1 from tb where zh=a.zh and flag>a.flag)
莫鸣 2012-12-12
  • 打赏
  • 举报
回复
谢谢,大家答案都不错。特别是前两位大哥。得到了句子,我慢慢研究先。

34,590

社区成员

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

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