SQL/SQL Grammar

[BigQuery] QUALIFY ๊ตฌ๋ฌธ

ISLA! 2024. 5. 20. 22:21

๐ŸŽฏ QUALIFY

  • ์ผ๋ฐ˜์ ์œผ๋กœ ์œˆ๋„์šฐ ํ•จ์ˆ˜์™€ ํ•จ๊ป˜ ์‚ฌ์šฉ๋จ
  • ํŠน์ • ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜๋Š” ํ–‰์„ ์„ ํƒํ•˜๊ฑฐ๋‚˜ ์ œ๊ฑฐํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋จ
  • ์œˆ๋„์šฐ ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ–‰์„ ํ•„ํ„ฐ๋ง ํ•˜๋Š”๋ฐ ์œ ์šฉํ•จ

 

์˜ˆ์‹œ ์ฟผ๋ฆฌ(1) : with ์ ˆ๊ณผ where ์‚ฌ์šฉ

  • order_id(์ฃผ๋ฌธ ์•„์ด๋””), amount(์ฃผ๋ฌธ ๊ธˆ์•ก)์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ํ…Œ์ด๋ธ”(orders)์—์„œ ์ฃผ๋ฌธ ์•„์ด๋””๋ณ„๋กœ ๊ฐ€์žฅ ๋†’์€ ๊ฐ€๊ฒฉ์˜ ๋ฌผ๊ฑด๋งŒ ๋ณด๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ, ๋‹ค์Œ๊ณผ ๊ฐ™์ด with ์ ˆ์„ ์ด์šฉํ•ด ์„œ๋ธŒ์ฟผ๋ฆฌ๋กœ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๋‹ค.
  • where ์ ˆ๋กœ ์กฐ๊ฑด์„ ๊ฑฐ๋Š” ๊ฒฝ์šฐ
WITH max_amount_per_order AS (
  SELECT
    order_id,
    amount,
    MAX(amount) OVER (PARTITION BY order_id) AS max_amount
  FROM
    orders
)
SELECT
  order_id,
  amount
FROM
  max_amount_per_order
WHERE
  amount = max_amount;

 

WHERE ์™€์˜ ์ฐจ์ด : ์ ์šฉ ์‹œ์ 

  • where
    • ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•˜๊ธฐ ์ „์— ํ•„ํ„ฐ๋ง์„ ์ˆ˜ํ–‰ํ•จ
    • ๋”ฐ๋ผ์„œ ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ์— ํฌํ•จ๋˜๋Š” ํ–‰์€ ๋ชจ๋‘ where ๊ตฌ๋ฌธ์˜ ์กฐ๊ฑด์„ ์ถฉ์กฑํ•˜๊ฒŒ ๋จ
  • qualify
    • ๋ฐ์ดํ„ฐ๋ฅผ ์กฐํšŒํ•œ ํ›„์— ์œˆ๋„์šฐ ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ–‰์„ ํ•„ํ„ฐ๋ง 
    • ๋”ฐ๋ผ์„œ ์œˆ๋„์šฐ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ์—๋งŒ ์ ์šฉ๋จ
    • ์ฆ‰, ์œˆ๋„์šฐ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ƒ์„ฑ๋œ ๊ฒฐ๊ณผ์— ๊ธฐ๋ฐ˜ํ•˜์—ฌ ํ–‰์„ ํ•„ํ„ฐ๋ง ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋จ

 

์˜ˆ์‹œ ์ฟผ๋ฆฌ(2) : qualify ์‚ฌ์šฉ

  • ์œ„์˜ ์˜ˆ์‹œ ์ฟผ๋ฆฌ๋ฅผ QUALIFY ๊ตฌ๋ฌธ์œผ๋กœ ์ข€ ๋” ์งง๊ฒŒ ์ฟผ๋ฆฌ๋ฅผ ์งค ์ˆ˜ ์žˆ๋‹ค.
  • ๊ฐ ์ฃผ๋ฌธ๋ณ„ ์ตœ๋Œ€๊ธˆ์•ก๊ณผ ๋™์ผํ•œ ๊ธˆ์•ก์„ ๊ฐ€์ง„ ํ–‰์„ ์„ ํƒํ•˜๊ฒŒ ๋˜์–ด ๋™์ผํ•œ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜๋ˆ๋‹ค
SELECT
  order_id,
  amount
FROM
  orders
QUALIFY
  amount = MAX(amount) OVER (PARTITION BY order_id);

 

์ฐธ๊ณ ์ž๋ฃŒ : https://docs.aws.amazon.com/ko_kr/redshift/latest/dg/r_QUALIFY_clause.html

 

QUALIFY ์ ˆ - Amazon Redshift

QUALIFY ์ ˆ QUALIFY ์ ˆ์€ ์‚ฌ์šฉ์ž๊ฐ€ ์ง€์ •ํ•œ ๊ฒ€์ƒ‰ ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ด์ „์— ๊ณ„์‚ฐ๋œ ์œˆ๋„์šฐ ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋ฅผ ํ•„ํ„ฐ๋งํ•ฉ๋‹ˆ๋‹ค. ์ด ์ ˆ์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•˜์œ„ ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์œˆ๋„์šฐ ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ์— ํ•„ํ„ฐ๋ง ์กฐ๊ฑด์„

docs.aws.amazon.com

 

728x90