日期:2014-05-17  浏览次数:20334 次

sql求最大,Orz

sflbh           sj      sl
050102       0 4.00
060101       0 1.00
050102       7 4.00
050102       11 2.00
050102       12 5.00
050102       13 2.00
050102       14 1.00
050102       16 1.00
060101       16 1.00
050102       20 2.00
060101       20 1.00
050102       23 4.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怎么取?取最大还是最小?
------其他解决方案--------------------