sql查询 分组后 每组某字段值最大的一行所有列
字段有:id、name、address、fenshu、update1n1a1s1200708012n2a1s2200703023n3a2s3200705014n3a1s7...
字段有: id、name、 address、 fenshu、 update
1 n1 a1 s1 20070801
2 n2 a1 s2 20070302
3 n3 a2 s3 20070501
4 n3 a1 s7 20070501
5 n3 a2 s4 20070301
6 n3 a2 s8 20070301
我想得到的数据是 按照 address 分组 然后取出每组中fenshu最大的那一条纪录。结果应该是这两条纪录:
1 n1 a1 s7 20070801
3 n3 a2 s8 20070501 展开
1 n1 a1 s1 20070801
2 n2 a1 s2 20070302
3 n3 a2 s3 20070501
4 n3 a1 s7 20070501
5 n3 a2 s4 20070301
6 n3 a2 s8 20070301
我想得到的数据是 按照 address 分组 然后取出每组中fenshu最大的那一条纪录。结果应该是这两条纪录:
1 n1 a1 s7 20070801
3 n3 a2 s8 20070501 展开
9个回答
展开全部
create table #a(address char(2),fenshu varchar(8))
insert into #a values ('a1','s1')
insert into #a values ('a1','s2')
insert into #a values ('a2','s3')
insert into #a values ('a1','s7')
insert into #a values ('a2','s4')
insert into #a values ('a2','s8')
insert into #a values ('a1','s8')
insert into #a values ('a2','s9')
实际语法测试 应该加上 分组条件区别,否则会有重复记录被取出(a.address = b.address)
select * from #a a
where fenshu in (
select max( fenshu) from #a b where a.address = b.address
group by address)
insert into #a values ('a1','s1')
insert into #a values ('a1','s2')
insert into #a values ('a2','s3')
insert into #a values ('a1','s7')
insert into #a values ('a2','s4')
insert into #a values ('a2','s8')
insert into #a values ('a1','s8')
insert into #a values ('a2','s9')
实际语法测试 应该加上 分组条件区别,否则会有重复记录被取出(a.address = b.address)
select * from #a a
where fenshu in (
select max( fenshu) from #a b where a.address = b.address
group by address)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
很容易
select *
from tab t
where not exists (select 1 from tab where address = t.address and fenshu > t.fenshu)
select *
from tab t
where not exists (select 1 from tab where address = t.address and fenshu > t.fenshu)
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select * from (
select id,name,counts,createDate,row_number() over(partition by name order by createDate desc) rn
from testTable
) t where t.rn <=1
参考链接:http://blog.csdn.net/sz_bdqn/article/details/7259738,分享给大家,是我的快乐!谢谢赞~o(∩_∩)o ~
select id,name,counts,createDate,row_number() over(partition by name order by createDate desc) rn
from testTable
) t where t.rn <=1
参考链接:http://blog.csdn.net/sz_bdqn/article/details/7259738,分享给大家,是我的快乐!谢谢赞~o(∩_∩)o ~
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select * from table a
where exists (
select 1 from table where id=a.id
group by address
having a.fenshu=max( fenshu))
where exists (
select 1 from table where id=a.id
group by address
having a.fenshu=max( fenshu))
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select id,name,address,fenshu,update from (select * ,row_number() over (partition by test3 order by test2 desc) tt from 表名) qq
where tt = 1
where tt = 1
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询