SQL中distinct的用法


在表中,可能會包含重復值。這並不成問題,不過,有時您也許希望僅僅列出不同(distinct)的值。關鍵詞 distinct用於返回唯一不同的值。

表A:

表B:

1.作用於單列

select distinct name from A

執行后結果如下:

2.作用於多列

示例2.1

select distinct name, id from A

執行后結果如下:

實際上是根據name和id兩個字段來去重的,這種方式Access和SQL Server同時支持。

示例2.2

select distinct xing, ming from B

返回如下結果:

返回的結果為兩行,這說明distinct並非是對xing和ming兩列“字符串拼接”后再去重的,而是分別作用於了xing和ming列。

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;

4.distinct必須放在開頭

select id, distinct name from A;   --會提示錯誤,因為distinct必須放在開頭

5.其他

distinct語句中select顯示的字段只能是distinct指定的字段,其他字段是不可能出現的。例如,假如表A有“備注”列,如果想獲取distinc name,以及對應的“備注”字段,想直接通過distinct是不可能實現的。但可以通過其他方法實現關於SQL Server將一列的多行內容拼接成一行的問題討論

 

原文鏈接:https://www.cnblogs.com/rainman/archive/2013/05/03/3058451.html#m0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM