๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/DB

[DB] GROUP BY ๊ฐ ๊ทธ๋ฃน์—์„œ ๋งˆ์ง€๋ง‰(์ตœ์‹ ) ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ

by ynzu๐Ÿค 2021. 12. 24.
๋ฐ˜์‘ํ˜•

GROUP BY๋Š” ์ง‘๊ณ„ ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋ฅผ ํŠน์ • ์นผ๋Ÿผ ๊ธฐ์ค€์œผ๋กœ ๋ฌถ์–ด ์ถœ๋ ฅํ•ด์ฃผ๋Š” ์ฟผ๋ฆฌ์ธ๋ฐ GROUP BY๋ฅผ ํ•˜๊ฒŒ ๋˜๋ฉด ํŠน์ • ์นผ๋Ÿผ๊ณผ ์ง‘๊ณ„ ํ•จ์ˆ˜ ์™ธ์— ๋‹ค๋ฅธ ์ปฌ๋Ÿผ์€ ์กฐํšŒํ•  ์ˆ˜๊ฐ€ ์—†๋‹ค.

PostgreSQL๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ๋‹ค๋ฅธ ์นผ๋Ÿผ์„ ์กฐํšŒํ•˜๋ ค๊ณ  ํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

SQL Error [42803]: ์˜ค๋ฅ˜: column "test.id" ๋Š” ๋ฐ˜๋“œ์‹œ GROUP BY ์ ˆ๋‚ด์— ์žˆ์–ด์•ผ ํ•˜๋˜์ง€ ๋˜๋Š” ์ง‘๊ณ„ ํ•จ์ˆ˜ ๋‚ด์—์„œ ์‚ฌ์šฉ๋˜์–ด์ ธ์•ผ ํ•œ๋‹ค


MySQL์€ GROUP BY์˜ ์นผ๋Ÿผ ์™ธ์—๋„ ์กฐํšŒ๊ฐ€ ๊ฐ€๋Šฅํ•˜์ง€๋งŒ ์ •ํ™•ํ•œ ๋ฐ์ดํ„ฐ๊ฐ€ ์•„๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํŠน์ • ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๊ตฌ์• ๋ฐ›์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค.

 


name ์นผ๋Ÿผ์„ group by ํ•˜์—ฌ ๋งˆ์ง€๋ง‰ ๋‚ ์งœ์˜ value๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ์ฟผ๋ฆฌ๋ฅผ ์ž‘์„ฑํ•˜๊ณ ์ž ํ–ˆ๋‹ค.

๋ฐ์ดํ„ฐ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

 

name๋ณ„ value์˜ ํ•ฉ๊ณ„๋Š” ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

select NAME, SUM(VALUE) from TEST group by NAME order by NAME;

๊ฒฐ๊ณผ

 

name๋ณ„ ๊ฐ€์žฅ ์ตœ์‹  ์ผ์ž๋„ ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

select NAME, max(CREATE_TIME) from TEST group by NAME order by NAME;

๊ฒฐ๊ณผ


ํ•˜์ง€๋งŒ name๋ณ„ value์˜ ํ•ฉ๊ณ„๊ฐ€ ์•„๋‹Œ, name๋ณ„ ์ตœ์‹  ์ผ์ž๊ฐ€ ์•„๋‹Œ name๋ณ„ ๋งˆ์ง€๋ง‰์œผ๋กœ ์ƒ์„ฑ๋œ value๋ฅผ ๊ตฌํ•ด์•ผ ํ–ˆ๋‹ค.

๋จผ์ € name๋ณ„ ๊ฐ€์žฅ ์ตœ์‹  ์ผ์ž๋ฅผ ์ถ”์ถœํ•˜๊ณ , ํ•ด๋‹น name๊ณผ ์ผ์ž๋ฅผ ์กฐ๊ฑด์œผ๋กœ ์ค˜์„œ ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์–ป์—ˆ๋‹ค.

select NAME, VALUE, CREATE_TIME 
	from TEST 
    where (NAME, CREATE_TIME) 
    in (
    	select NAME, max(CREATE_TIME) as CREATE_TIME 
        	from TEST 
            group by NAME
       )
    order by NAME;

๊ฒฐ๊ณผ

 

 

โ€ปWHERE ์ ˆ์˜ IN ์‚ฌ์šฉ๋ฒ•

WHERE ์นผ๋Ÿผ IN (์กฐ๊ฑด1, ์กฐ๊ฑด2, ์กฐ๊ฑด3)

 

: WHERE ๋’ค์˜ ์นผ๋Ÿผ๋“ค๊ณผ IN ๋’ค์˜ ์กฐ๊ฑด๋“ค์ด ์ผ์น˜ํ•˜๋Š” ROW๋ฅผ ๊ฐ€์ ธ์˜ค๊ฒŒ ๋œ๋‹ค. ๋‚˜์—ดํ•œ ์กฐ๊ฑด๋“ค์€ OR ์กฐ๊ฑด์œผ๋กœ ์กฐํšŒ๋œ๋‹ค. 

WHERE NAME = 'A'
OR NAME = 'B'
WHERE NAME IN ('A','B')

๋‘๊ฐœ์˜ ๊ฒฐ๊ณผ๊ฐ€ ๊ฐ™๋‹ค

 

๋ฐ˜๋Œ€๋กœ WHERE ์นผ๋Ÿผ NOT IN (์กฐ๊ฑด1, ์กฐ๊ฑด2, ...) ๋Š” ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•  ์ˆ˜ ์žˆ๋‹ค.

 


But ์ด ๊ฒฝ์šฐ ๊ฐ™์€ ์‹œ๊ฐ„์ด ์กด์žฌํ•œ๋‹ค๋ฉด ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธด๋‹ค...

name๊ณผ create_time์ด ๋™์ผํ•œ ๋ฐ์ดํ„ฐ๊ฐ€ ์กด์žฌํ•œ๋‹ค๋ฉด ์œ„ ์ฟผ๋ฆฌ๋ฅผ ์‹คํ–‰ํ–ˆ์„ ๋•Œ ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค

 

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€