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

SQL怎么去掉查询结果的重复数据

2012-04-22 
SQL如何去掉查询结果的重复数据?select top 10 a from ta order by b desc.目的是取出依照b排序的a数据 其

SQL如何去掉查询结果的重复数据?
select top 10 a from ta order by b desc.
目的是取出依照b排序的a数据 其中b是不会重复的查询出的a是重复的,如何去掉!
例如 以下数据
a b
我 1
我 2
你 3
他 4
她 5
她 6
需要得到的数据是




这样的顺序!

[解决办法]

SQL code
select a,max(b) as mb from ta order by max(b)
[解决办法]
探讨

SQL code
select a,max(b) as mb from ta order by max(b)

[解决办法]
select distinct a from ta order by b desc


[解决办法]

这个问题看似简单,其实挺复杂的,我也没想出来。还是等下面高手来解答的吧。
[解决办法]
探讨
select top 10 a
from ta t
where not exists(select 1 from ta where a = t.a and b > t.b)
order by b desc
这样可以 但是查询时间过长,可以优化吗?谢谢大家

[解决办法]
探讨
select top 10 a
from ta t
where not exists(select 1 from ta where a = t.a and b > t.b)
order by b desc
这样可以 但是查询时间过长,可以优化吗?谢谢大家

[解决办法]
SQL code
declare @tb table (a nvarchar(12),b int)insert @tb  select '我',1 union allselect '我',2 union allselect '你',3 union allselect '他',4 union allselect '她',5 union allselect '她',6select a from (select  top (100) ROW_NUMBER() over(PARTITION by a order by a desc)rn ,a,b  from @tb group by a,b order by b desc) aawhere rn=1/*a她他你我*/
[解决办法]
select a from ta group by a order by max(b) desc
[解决办法]
CREATE TABLE tmp AS SELECT MIN(b) as id FROM ta GROUP BY a;
DELETE FROM ta WHERE id NOT IN (SELECT id FROM tmp )
DROP TABLE tmp

然后 select * from ta order by b desc
[解决办法]
select a,max(b) 
from ta
group by a
order by b desc

酱紫不可以吗?
[解决办法]
distinct
[解决办法]
SQL code
CREATE TABLE TEST2(    Name VARCHAR(10),    Id INT)GOINSERT INTO TEST2SELECT '我',1 UNIONSELECT '我',2 UNIONSELECT '你',3 UNIONSELECT '他',4 UNIONSELECT '她',5 UNIONSELECT '她',6SELECT NAMEFROM TEST2GROUP BY NameORDER BY MAX(ID) DESC
[解决办法]
distinct
[解决办法]
select top 10 a from( select distinct a,max(b) as b from ta group by b) table_A order by b desc 

[解决办法]
探讨
select top 10 a from ta order by b desc.
目的是取出依照b排序的a数据 其中b是不会重复的查询出的a是重复的,如何去掉!
例如 以下数据
a b
我 1
我 2
你 3
他 4
她 5
她 6
需要得到的数据是




这样的顺序!

[解决办法]
之前在英文系统里,写错了。。
------解决方案--------------------


SQL code
-- 数据create table tb(mm varchar(20),nn int)insert tb values('我',1);insert tb values('我',2);insert tb values('你',3);insert tb values('他',4);insert tb values('她',5);insert tb values('她',6);-- 查询select mm from (    select r=row_number() over (partition by mm order by nn), * from tb) a where a.r=1order by nn desc 

热点排行