zoukankan      html  css  js  c++  java
  • SQL中distinct的用法(转)

    原文:http://www.cnblogs.com/rainman/archive/2013/05/03/3058451.html

    在表中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。关键词 distinct用于返回唯一不同的值。

    表A:

    表B:

    表newTest:

    --------------------------------------------------------

    1.作用于单列

    SQL语句:
    select distinct name from A

    执行后结果如下:

    SQL语句:
    select distinct sex from newTest

    执行后结果如下:

    SQL语句:
    select distinct age from newTest

    执行后结果如下:

    --------------------------------------------------------

    2.作用于多列

    SQL语句:
    select distinct name, id from A

    执行后结果如下:

    实际上是根据name和id两个字段来去重的,这种方式Access和SQL Server同时支持。

    SQL语句:
    select distinct xing, ming from B

    执行后结果如下:

    返回的结果为两行,这说明distinct并非是对xing和ming两列“字符串拼接”后再去重的,而是分别作用于了xing和ming列。

    更多例子:

    SQL语句:
    select distinct sex,age from newTest

    执行后结果如下:

    --------------------------------------------------------

    3.COUNT统计

    select count(distinct name) from A;      --表中name去重后的数目, SQL Server支持,而Access不支持

    count是不能统计多个字段的,下面的SQL在SQL Server和Access中都无法运行。

    select count(distinct name, id) from A;

    若想使用,请使用嵌套查询,如下:

    select count(*) from (select distinct xing, name from B) AS M;

    --------------------------------------------------------

    其他注意事项:

    distinct必须放在开头

    select id, distinct name from A;   --会提示错误,因为distinct必须放在开头

    显示

    distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。例如,假如表A有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。但可以通过其他方法实现关于SQL Server将一列的多行内容拼接成一行的问题讨论

  • 相关阅读:
    2.4.6 处理表单 的 工作原理的解释
    nginx proxy模块
    nginx负载均衡模块
    Oracle正在执行和执行过的SQL语句
    nginx
    linux :故障提示:Error:No suitable device found: no device found for connection "System eth0"
    memcached
    一致性哈希算法(consistent hashing)(转)
    大规模网站sesson会话保持思路及实践配置
    AB压力测试工具
  • 原文地址:https://www.cnblogs.com/start-from-scratch/p/5635608.html
Copyright © 2011-2022 走看看