读书人

sql求最大Orz,该怎么解决

发布时间: 2012-12-16 12:02:32 作者: rapoo

sql求最大,Orz


sflbh sj sl
050102 04.00
060101 01.00
050102 74.00
050102 112.00
050102 125.00
050102 132.00
050102 141.00
050102 161.00
060101 161.00
050102 202.00
060101 201.00
050102 234.00

我想根据sflbh求出sl最大值 同时还列出sj列怎么写?
select sflbh,max(sl) from table
group by sflbh 然后需要对应的sj列
[最优解释]

select
*
from
TB t
where
not exists(select 1 from TB where sflbh=t.sflbh and sl>t.sl)

[其他解释]
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
GO
create table [TB]([sflbh] varchar(6),[sj] int,[sl] numeric(3,2))
insert [TB]
select '050102',0,4.00 union all
select '060101',0,1.00 union all
select '050102',7,4.00 union all
select '050102',11,2.00 union all
select '050102',12,5.00 union all
select '050102',13,2.00 union all
select '050102',14,1.00 union all
select '050102',16,1.00 union all
select '060101',16,1.00 union all
select '050102',20,2.00 union all
select '060101',20,1.00 union all
select '050102',23,4.00

select
sflbh,
[sj]=STUFF((SELECT ','+RTRIM(sj) FROM TB WHERE t.[sflbh]=[sflbh] FOR XML PATH('')),1,1,''),
[sl]=max(sl) from TB t
group by sflbh


drop table [TB]


[其他解释]
select sflbh,max(sl),sj from 表1 
group by sflbh,sj

[其他解释]
引用:
SQL code
?



1234567891011121314151617181920212223242526

--> 测试数据:[TB] if object_id('[TB]') is not null drop table [TB] GO create table [TB]([sflbh] varchar(6),[sj] int,[sl] numeric(3,2)) ins……

我不是把所有的sj全部列出来。我只要列出最大值所对应的sj就可以了
[其他解释]
引用:
引用:SQL code
?



1234567891011121314151617181920212223242526

--> 测试数据:[TB] if object_id('[TB]') is not null drop table [TB] GO create table [TB]([sflbh] varchar(……

那如果最大值对应那列有几个sj怎么取?取最大还是最小?
------其他解决方案--------------------



select a.sflbh,a.sl,a.sj
from [table] a
inner join
(select sflbh,max(sl) 'maxsl'
from [table] group by sflbh) b
on a.sflbh=b.sflbh and a.sl=b.maxsl

[其他解释]
sl 最大值会有一样的,所以显示出来有几笔
[其他解释]
引用:
SQL code
?



1234567

select * from TB t where not exists(select 1 from TB where sflbh=t.sflbh and sl>t.sl)

谢谢这办法最好

读书人网 >SQL Server

热点推荐