sqlserver2005前:
--分組取最大最小常用sql
--測試環境
if OBJECT_ID('tb') is not null drop table tb;
go
create table tb(
col1 int,
col2 int,
Fcount int)
insert into tb
select 11,20,1 union all
select 11,22,1 union all
select 11,23,2 union all
select 11,24,5 union all
select 12,39,1 union all
select 12,40,3 union all
select 12,38,4
go
--查詢
--1
select * from tb t where Fcount=(select max(Fcount)from tb where col1=t.col1)
--2
select * from tb t where not exists(select 1 from tb where col1=t.col1 and Fcount>t.Fcount) --效率要高很多(lui2015-5-13注釋)
--結果
/*
col1 col2 Fcount
----------- ----------- -----------
12 38 4
11 24 5
*/
====================================================
====================================================
【SQL Server 2005后推薦使用這種方式】
--1.創建測試表
create table #score
(
name varchar(20),
subject varchar(20),
score int
)
--2.插入測試數據
insert into #score(name,subject,score) values('張三','語文',98)
insert into #score(name,subject,score) values('張三','數學',80)
insert into #score(name,subject,score) values('張三','英語',90)
insert into #score(name,subject,score) values('李四','語文',88)
insert into #score(name,subject,score) values('李四','數學',86)
insert into #score(name,subject,score) values('李四','英語',88)
insert into #score(name,subject,score) values('李明','語文',60)
insert into #score(name,subject,score) values('李明','數學',86)
insert into #score(name,subject,score) values('李明','英語',88)
insert into #score(name,subject,score) values('林風','語文',74)
insert into #score(name,subject,score) values('林風','數學',99)
insert into #score(name,subject,score) values('林風','英語',59)
insert into #score(name,subject,score) values('嚴明','英語',96)
--3.取每個學科的前3名數據
select * from
(
select subject,name,score,ROW_NUMBER() over(PARTITION by subject order by score desc) as num from #score
) T where T.num <= 3 order by subject
--4.刪除臨時表
truncate table #score
drop table #score
解釋:根據COL1分組,在分組內部根據 COL2排序,而此函數計算的值就表示每組內部排序后的順序編號(組內連續的唯一的)
==========================================
===========================================
oracle 分組取最大值方式
select distinct id, to_char(First_value(STARTTIME) OVER (PARTITION BY id order by to_number(VALUE) desc),'yyyy-mm-dd hh24:mi:ss') as STARTTIME,
First_value(ENNAME) OVER (PARTITION BY id order by to_number(VALUE) desc) as ENNAME,
First_value(VALUE) OVER (PARTITION BY id order by to_number(VALUE) desc) as maxvalue
from tab_obj_rtatt_data_old where
Upper(ltrim(rtrim(ENNAME))) =?
AND STARTTIME>=to_date(?,'YYYY-MM-DD HH24:MI:SS')
AND STARTTIME<=to_date(?,'YYYY-MM-DD HH24:MI:SS')