当前位置: 代码迷 >> Sql Server >> SQL怎么去掉查询结果的重复数据
  详细解决方案

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

热度:17   发布时间:2016-04-27 13:17:14.0
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
需要得到的数据是
她
他
你
我
这样的顺序!

------解决方案--------------------
之前在英文系统里,写错了。。
------解决方案--------------------
  相关解决方案