http://topic.csdn.net/u/20091016/09/fea7e9d3-53c4-4b00-9abe-dbf8dd55b05b.html?seed=1546300155&r=60454236#r_60454236
原问题:
数据如下, 我想取出TABLE中的数据, 按照下面的条件.
如果F2相同的情况下, 取F3数据较小的那条, 如果F3还相同, 就取F4较小的那个, 依次...
请教简单点效率高点的SQL, 因为数据较多, 不想那么复杂
Data:
F1 F2 F3 F4 F5
A A1 2 4 6
A A1 1 8 9
B B1 4 6 2
B B1 4 9 7
C C2 1 4 5
C C2 1 4 4
Result:
F1 F2 F3 F4 F5
A A1 1 8 9
B B1 4 6 2
C C2 1 4 4
可使用的脚本如下:
create table tt1([F1] nvarchar(1),[F2] nvarchar(2),[F3] int,[F4] int,[F5] int)
Insert into tt1
select N'A',N'A1',2,4,6 union all
select N'A',N'A1',1,8,9 union all
select N'B',N'B1',4,6,2 union all
select N'B',N'B1',4,9,7 union all
select N'C',N'C2',1,4,5 union all
select N'C',N'C2',1,4,4
一、
select *
from tt1 t
where not exists( select 1
from tt1
where (F2 = T.F2 and F3 < t.F3)
or (F2 = T.F2 and F3 = t.F3 and F4 < t.F4)
or (F2 = T.F2 and F3 = t.F3 and F4 = t.F4 and F5 < t.F5))
二、
select *
from tt1 t
where not exists( select 1
from tt1
where [f1]=t.[f1]
and (([f2] < t.[f2])
or ([f2] = t.[f2] and ([f3] < t.[f3]))
or ([f3] = t.[f3] and ([f4] < t.[f4]) or (f4 = t.[f4] and [f5] < t.[f5]))
)
)
三、
;with C
as
(
Select *,Row = Row_number() over(partition by [F1] Order by [F2],[F3],[F4],[F5])
from tt1
)
select F1, F2, F3, F4, F5
from c
where Row=1
四、
select *
from tt1 a
where checksum(*)=( select top 1 checksum(*)
from tt1
where [F1]=a.[F1]
order by [F2],[F3],[F4],[F5])