求最大的唯一值
表格如下
a b c d
84111
84116
84115
84113
84114
84112
84111
84121
84125
84125
84131
.. ......................
希望得到以下结果
84116
84131
a/b/c 列决定 每行的最大值,而且是唯一的。
84125 就被排除了。
[最优解释]
SQL SERVER 2000不支持with表达式。
嵌套一下就可以了。
declare @T table (a int,b int,c int,d int)
insert into @T
select 8,4,11,1 union all
select 8,4,11,6 union all
select 8,4,11,5 union all
select 8,4,11,3 union all
select 8,4,11,4 union all
select 8,4,11,2 union all
select 8,4,11,1 union all
select 8,4,12,1 union all
select 8,4,12,5 union all
select 8,4,12,5 union all
select 8,4,13,1
select * from
(
select * from @T t
where d=(select max(d) from @T where a=t.a and b=t.b and c=t.c)
) a
group by a,b,c,d having(count(1)=1)
--> 测试数据: @T
declare @T table (a int,b int,c int,d int)
insert into @T
select 8,4,11,1 union all
select 8,4,11,6 union all
select 8,4,11,5 union all
select 8,4,11,3 union all
select 8,4,11,4 union all
select 8,4,11,2 union all
select 8,4,11,1 union all
select 8,4,12,1 union all
select 8,4,12,5 union all
select 8,4,12,5 union all
select 8,4,13,1
;with maco as
(
select * from @T t
where d=(select max(d) from @T where a=t.a and b=t.b and c=t.c)
)
select * from maco
group by a,b,c,d having(count(1)=1)
/*
a b c d
----------- ----------- ----------- -----------
8 4 11 6
8 4 13 1
*/
select 8,4,11,3 union all
select 8,4,11,4 union all
select 8,4,11,2 union all
select 8,4,11,1 union all
select 8,4,12,1 union all
select 8,4,12,5 union all
select 8,4,12,5 union all
select 8,4,13,1
;with maco as( select * from @T t where d=(select max(d) from @T where a=t.a and b=t.b and c=t.c) ) select * from maco group by a,b,c,d having(count(1)=1)
(11 行受影响)
a b c d
----------- ----------- ----------- -----------
8 4 11 6
8 4 13 1
(2 行受影响)