簡體   English   中英

GROUP BY和DISTINCT有什么區別?

[英]What is the difference between GROUP BY and DISTINCT?

我有以下數據的表格

empid   empname deptid   address
--------------------------------
aa76    John     6       34567
aa75    rob      4       23456
aa71    smith    3       12345
aa74    dave     2       12345
a77     blake    2       12345
aa73    andrew   3       12345
aa90    sam      1       12345
aa72    will     6       34567
aa70    rahul    5       34567

我使用了以下查詢:

select deptid, EMPID ,EMPNAME ,ADDRESS
from mytable
group by 1,2,3,4

結果如下:

deptid  empid  empname address
------------------------------
1       aa90   sam      12345
2       aa74   dave     12345
2       aa77   blake    12345
3       aa71   smith    12345
3       aa73   andrew   12345
4       aa75   rob      23456
5       aa70   rahul    34567
6       aa76   John     34567
6       aa72   will     34567

並為查詢:

select distinct (deptid),EMPID,EMPNAME,ADDRESS
from mytable

結果集是:

deptid empid empname address   
----------------------------
1      aa90  sam     12345
2      aa74  dave    12345
2      aa77  blake   12345
3      aa71  smith   12345
3      aa73  andrew  12345
4      aa75  rob     23456
5      aa70  rahul   34567
6      aa72  will    34567
6      aa76  John    34567

在第二個查詢中雖然我已經為DEPTID提供了DISTINCT ,但為什么我得到重復的DEPTID ...

你能解釋一下嗎?

DISTINCT消除了重復的行。 GROUP BY唯一記錄進行分組,並允許您執行聚合函數。

DISTINCT作為一個整體引用不同的記錄,而不是記錄中的不同字段。

DISTINCT僅適用於整行。 不要誤導SELECT DISTINCT(A), B做不同的事情。 這相當於SELECT DISTINCT A, B

雖然所有列和不同的分組將在Teradata中給出相同的結果,但它們在幕后具有不同的算法,並且通常使用group by比使用distinct更好。 我相信有計划以同樣的方式實現,但它們在我使用的版本(v2r6)中仍然不同,我還沒有嘗試過Teradata 12。

Group By和Distin都將工作相同。 與Distinct Group相比通過提供良好的性能,因為它處理的行數更少,占用的假脫機內存更少

使用多列時,Distinct無法正常工作。 雖然在單列上給出了不同但它給出了指定列的唯一組合。

因此,Group by提供了唯一的記錄,也可以進行聚合。

我不知道如何解釋差異,但我給你舉例_with_queries_通過這個你可以更好地理解GROUP BYDISTINCT之間的區別。

問題:在customers表中,每個獨特狀態中有多少人

select distinct(state), count(*) from customers;

RESULT

Washington  17
----------------------------------------------------------

select State, count(*) from customers GROUP BY STATE;

RESULT

**Arizona    6
Colorado         2
Hawaii           1
Idaho            1
North Carolina   1
Oregon           2
Sourth Carolina  1
Washington   2
Wisconsin    1**

只需制作自己的表格並檢查結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM