What is the difference between GROUP BY and DISTINCT?

I have a table with the following data

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

I used the following queries:

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

Which gives the result:

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

And for the request:

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

Result set:

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

In the second query, although I gave DISTINCTfor the DEPTID, where did I get the duplicate DEPTID ...

Could you explain this?

+3
source share
7 answers

DISTINCT refer to individual records as a whole, and not to individual fields in a record.

+6
source

DISTINCTeliminates duplicate lines. GROUP BYgroups unique records and allows you to perform aggregate functions.

+9
source

DISTINCT . . SELECT DISTINCT(A), B - . SELECT DISTINCT A, B

+2

Teradata, , , . , , , , (v2r6), Teradata 12.

+1

By Distinct . . ,

0

. , .

, Group by .

-1

, , _with_queries_, GROUP BY DISTINCT.

:

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**

-1

Source: https://habr.com/ru/post/1722653/


All Articles