日期:2014-05-18  浏览次数:20674 次

SQL server中的Select DISTINCT对某个字段约束的用法?
下面先来看看例子:
表:table
字段:id   name
            1     a
            2     b
            3     c
            4     c
            5     b
——目标:我想用一条语句查询得到name不重复的所有数据:

(1)select   distinct   name   from   table
得到的结果是:
    name
    a
    b
    c
好像达到效果了,可是,我想要得到的是id值呢?
(2)改一下查询语句吧:   select   distinct   name,   id   from   table
结果会是:
    id   name
    1   a
    2   b
    3   c
    4   c
    5   b
distinct怎么没起作用?作用是起了的,不过他同时作用了两个字段,也就是必须得id与name都相同的才会被排除。。。。。。。

(3)我们再改改查询语句:   select   id,   distinct   name   from   table
很遗憾,除了错误信息你什么也得不到,distinct必须放在开头。难到不能把distinct放到where条件里?能,照样报错。。。。。。。

(4)用count写:select   id,   name,   count(distinct   name)   from   table   group   by   name

结果报错:
服务器:   消息   8120,级别   16,状态   1,行   1
Column   'table.id '   is   invalid   in   the   select   list   because   it   is   not   contained   in   either   an   aggregate   function   or   the   GROUP   BY   clause.

——求救:该怎么写?才能实现这个目标呢?


------解决方案--------------------
select * from tablename a where not exists(select 1 from tablename where a.name = name and a.id > id)
------解决方案--------------------
select name , min(id) id from tb group by name