首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求最大的独一值

2012-12-16 
求最大的唯一值表格如下abcd8411184116841158411384114841128411184121841258412584131..................

求最大的唯一值
表格如下

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
*/

[其他解释]
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 


  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 行受影响)

热点排行
Bad Request.