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

[Oracle] ๋ฐ์ดํ„ฐ์—†๋Š” ์ปฌ๋Ÿผ์— 0 ํ‘œ๊ธฐํ•˜๊ธฐ NVL , LEFT JOIN

by yunamom 2022. 3. 25.
๋ฐ˜์‘ํ˜•

์•ˆ๋…•ํ•˜์„ธ์š” :D yunamom ์ž…๋‹ˆ๋‹ค.

 

์ •๋ณด์ฒ˜๋ฆฌ ์‚ฐ์—…๊ธฐ์‚ฌ ์‹ค๊ธฐ๋ฌธ์ œ๋ฅผ ์—ฐ์Šตํ•˜๋‹ค๊ฐ€ ๋ฐ์ดํ„ฐ์—†๋Š” ์ปฌ๋Ÿผ์— 0์œผ๋กœ ํ‘œ๊ธฐํ•˜๋Š”๋ฒ•์„ ์ •๋ฆฌํ•ด๋‘๋ ค๊ณ  ํฌ์ŠคํŒ…ํ•ฉ๋‹ˆ๋‹ค.๐Ÿ˜Š

 

๐Ÿ‘‡์•„๋ž˜๋Š” ์ถœ๋ ฅํ•ด์•ผํ•˜๋Š” ํ™”๋ฉด์ž…๋‹ˆ๋‹ค.

๋ณ‘์›์ง€์—ญ ๋ณ‘์›์ง€์—ญ๋ช… ์ ‘์ข…์˜ˆ์•ฝ๊ฑด์ˆ˜
10 ์„œ์šธ 5
20 ๋Œ€์ „ 3
30 ๋Œ€๊ตฌ 2
40 ๊ด‘์ฃผ 0
์ดํ•ฉ 10
  1. ๋ณ‘์›์ด ์žˆ๋Š” ์ง€์—ญ๋ณ„๋กœ ์ ‘์ข…์˜ˆ์•ฝ๊ฑด์ˆ˜์˜ ํ•ฉ์„ ์ถœ๋ ฅํ•จ.
  2. ๋ชจ๋“  ๋ณ‘์›์˜ ์ ‘์ข…์˜ˆ์•ฝ๊ฑด์ˆ˜๋ฅผ ํ•ฉ์ณ์„œ ์ดํ•ฉ์„ ์ถœ๋ ฅํ•จ.
  3. (๋ณ€ํ˜•) ๊ธฐ์กด ๋ฌธ์ œ๋Š” ๊ด‘์ฃผ์ง€์—ญ์˜ ๊ฒฝ์šฐ ์˜ˆ์•ฝ๊ฑด์ˆ˜๊ฐ€ ์—†์–ด ์ถœ๋ ฅ์„ ํ•˜์ง€ ์•Š์•˜์œผ๋‚˜, ์˜ˆ์•ฝ์ด ์—†๋Š” ๊ฒฝ์šฐ 0์œผ๋กœ ํ‘œ๊ธฐํ•˜์—ฌ ์ถœ๋ ฅํ•จ.

LEFT JOIN ์œผ๋กœ ์˜ค๋ฅธ์ชฝ ๋ฐ์ดํ„ฐ ๊ฐ’์ด ์—†๋”๋ผ๋„ ์™ผ์ชฝ ํ…Œ์ด๋ธ” ์ปฌ๋Ÿผ์€ ์ถœ๋ ฅํ• ์ˆ˜์žˆ๋Š” ์ฟผ๋ฆฌ๋ฌธ

 

์ฒ˜์Œ์— count(*) ๋กœ ํ•˜์˜€๋”๋‹ˆ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†๋”๋ผ๋„ 1์ด๋‚˜์™€์„œ ์ด๋Ÿฐ๊ฒฝ์šฐ ๋ฐ์ดํ„ฐ๊ฐ€ ์ •๋ง 1์ด ์žˆ๋Š”๊ฒฝ์šฐ๋ž‘ ๊ฒน์ณ์„œ ์•„์ฃผ ๊ณค๋ž€ํ•œ๋ฐ 

 

์ €๋…ธ๋ฌด 1์„ 0์œผ๋กœ ๋ฐ”๊ฟ€๋ ค๊ณ  UNION ์ด๋ฉฐ OUTER JOIN..์ด๋ฉฐ ๋Œ€์ž…ํ•ด๋ดค์ง€๋งŒ 0์ด ๋‚˜์˜ค์ง€์•Š์•˜๋‹ค.

 

๊ทธ๋Ÿฐ๋ฐ ์–ธ์ œ๋‚˜ ๊ทธ๋ ‡๋“ฏ!!!! ๋‹ต์€ ๋ญ์ด๋ฆฌ ๊ฐ„๋‹จํ•œ๊ฐ€ ๊ทธ๋ƒฅ count(V.hospcode) ๋„ฃ์–ด์ฃผ๋ฉด ๋˜๋Š”๊ฑฐ์˜€๋‹ค. ํ—ˆํ—ˆํ—ˆ ๋„ˆ๋ฌด ๋ณต์žกํ•˜๊ฒŒ ์ƒ๊ฐํ–ˆ๋˜๊ฑฐ ๊ฐ™๋‹ค

SELECT 

	H.hospaddr,
	DECODE(H.hospaddr,'10','์„œ์šธ','20','๋Œ€์ „','30','๋Œ€๊ตฌ','๊ด‘์ฃผ')name, 
	NVL(count(V.hospcode),'0')cnt 
    
FROM TBL_HOSP_202108 H 
	LEFT JOIN TBL_VACCRESV_202108 V 
    
	ON H.hospcode = V.hospcode 
	GROUP BY hospaddr
    
ORDER BY cnt DESC;

ORDER BY ๋กœ ์ •๋ ฌํ›„

SELECT 

	H.hospaddr AS ๋ณ‘์›์ง€์—ญ, 
    DECODE(H.hospaddr,'10','์„œ์šธ','20','๋Œ€์ „','30','๋Œ€๊ตฌ','๊ด‘์ฃผ') AS ๋ณ‘์›์ง€์—ญ๋ช…, 
    NVL(count(V.hospcode),'0') AS ์ ‘์ข…์˜ˆ์•ฝ๊ฑด์ˆ˜ 
    
FROM TBL_HOSP_202108 H 
	LEFT JOIN TBL_VACCRESV_202108 V 
    
    ON H.hospcode = V.hospcode 
    GROUP BY hospaddr
    
ORDER BY ์ ‘์ข…์˜ˆ์•ฝ๊ฑด์ˆ˜ DESC;

 

 

300x250

์ฝ”๋“œ