๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
SQL/SQL test

[HackerRank] SQL Project Planning

by ISLA! 2024. 1. 17.

Advanced Join / Intermediate

๋ฌธ์ œ

๐Ÿ‘‰ ๋ฌธ์ œ ๋งํฌ : https://www.hackerrank.com/challenges/sql-projects/problem?isFullScreen=true

  • ๋‹ค์Œ๊ณผ ๊ฐ™์€ ํ…Œ์ด๋ธ”์—์„œ end_date์™€ start_date๊ฐ€ ์—ฐ์†์ ์œผ๋กœ ์ด์–ด์ง€๋ฉด ํ•˜๋‚˜์˜ ํ”„๋กœ์ ํŠธ๋กœ ๊ฐ„์ฃผํ•œ๋‹ค.
  • Start_Date ๊ณ ์œณ๊ฐ’์€ Start_date๊ฐ€ End_Date์™€ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ด๋ฉฐ, End_Date ๊ณ ์œณ๊ฐ’ ์—ญ์‹œ, Start_date์™€ ์ผ์น˜ํ•˜์ง€ ์•Š์œผ๋ฉด ํ•˜๋‚˜์˜ ํ”„๋กœ์ ํŠธ์˜ ์‹œ์ž‘์ผ๊ณผ ์ข…๋ฃŒ์ผ์ด ๋œ๋‹ค.
  • ์ด ํฌ์ธํŠธ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค


ํ’€์ด

 

  • FROM ์ ˆ์— ๋‘ ๊ฐœ์˜ ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ๋„ฃ๋Š”๋‹ค. ๊ฐ๊ฐ ํ”„๋กœ์ ํŠธ๋ณ„ ๊ณ ์œ ํ•œ ์‹œ์ž‘์ผ๊ณผ ์ข…๋ฃŒ์ผ์„ ์ถ”์ถœํ•˜๋Š” ๊ฒƒ์ด๋‹ค.
    • WHERE ์ ˆ์— ์‹œ์ž‘์ผ์ด ์ข…๋ฃŒ์ผ์— ํฌํ•จ๋˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋ฅผ ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ ์œ„ํ•ด SELECT ์ ˆ์„ ํ•œ๋ฒˆ ๋” ์ผ๋‹ค.
    • ์œ„ ์ด๋ฏธ์ง€์— ํ‘œ์‹œ๋œ 1๊ณผ 2์˜ ๋กœ์ง์€ ๋™์ผํ•˜๋‹ค.
  • ์ตœ์ƒ๋‹จ SELECT์ ˆ์— ๋‘ FROM ์ ˆ์˜ ํ…Œ์ด๋ธ”๋กœ๋ถ€ํ„ฐ ์‹œ์ž‘์ผ๊ณผ ์ข…๋ฃŒ์ผ์„ ๋ฐ›์•„์˜ฌ ์ˆ˜ ์žˆ๋‹ค.
  • ์ด๋•Œ, WHERE ์ ˆ์— ์‹œ์ž‘์ผ๋ณด๋‹ค ์ข…๋ฃŒ์ผ์ด ์ด๋ฅธ(์ž‘์€) ๊ฒฝ์šฐ๋กœ ํ•„ํ„ฐ๋ง์„ ๊ฑธ์–ด์ค€๋‹ค.
  • ์‹œ์ž‘์ผ์„ ๊ธฐ์ค€์œผ๋กœ GROUP BY ํ•˜๊ณ , ์ข…๋ฃŒ์ผ์˜ ์ตœ์†Ÿ๊ฐ’์„ ์ง€์ •ํ•ด์ฃผ๋ฉด ์›ํ•˜๋Š” ๋‹ต์ด ๋‚˜์˜จ๋‹ค.(์ตœ์†Ÿ๊ฐ’ ์ ์šฉ์ „๊ณผ, ์›๋ž˜ ๋ฐ์ดํ„ฐ๋ฅผ ๋น„๊ตํ•ด๋ณด๋ฉด ์•Œ ์ˆ˜ ์žˆ๋‹ค)
  • ORDER BY ์กฐ๊ฑด์— DATEDIFF๋ฅผ ์จ์„œ ํ”„๋กœ์ ํŠธ ๊ธฐ๊ฐ„์„ ์‚ฐ์ถœํ•ด์ค€๋‹ค.
SELECT Start_Date, MIN(End_Date)
FROM(
    SELECT Start_Date
    FROM Projects
    WHERE Start_Date NOT IN (SELECT End_Date FROM Projects)) AS a,
    (SELECT End_Date
     FROM Projects
     WHERE End_Date NOT IN (SELECT Start_Date FROM Projects)) AS b
WHERE Start_Date < End_Date
GROUP BY 1
ORDER BY DATEDIFF(MIN(End_Date), Start_Date), Start_Date;
728x90

'SQL > SQL test' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[HackerRank] Interviews (Advanced Join) ํ’€์ด  (2) 2024.01.17
[HackerRank] Occupations (Pivot)  (0) 2024.01.17
[HackerRank] Contest Leaderboard  (0) 2024.01.16
[HackerRank] Challenges  (0) 2024.01.16
[HackerRank] The Report (INNER JOIN - BETWEEN)  (0) 2024.01.15