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

求最大的唯一值
表格如下

a       b       c       d

8 4 11 1
8 4 11 6
8 4 11 5
8 4 11 3
8 4 11 4
8 4 11 2
8 4 11 1

8 4 12 1
8 4 12 5
8 4 12 5

8 4 13 1

..  ......................

希望得到以下结果

8 4 11 6
8 4 13 1


a/b/c 列决定  每行的最大值,而且是唯一的。

8 4 12 5 就被排除了。



------最佳解决方案--------------------
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
*/

------其他解决方案--------------------
2000系统

服务器: 消息 156,级别 15,状态 1,行 14
在关键字 '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