Tools/- SQL

[SQL] solvesql ๊ฐ€๊ตฌ ํŒ๋งค์˜ ๋น„์ค‘์ด ๋†’์•˜๋˜ ๋‚  ์ฐพ๊ธฐ

์Šค์œ„๋ฏผ 2025. 1. 16. 15:13

๋ฌธ์ œ

https://solvesql.com/problems/day-of-furniture/

 

https://solvesql.com/problems/day-of-furniture/

 

solvesql.com

 

์ฝ”๋“œ ์ „๋ฌธ

1์ฐจ ์‹œ๋„

with
  calc as (
    SELECT
      order_date,
      count(*) AS total_orders,
      count(
        CASE
          WHEN category = 'Furniture' THEN 1
          ELSE 0
        END
      ) AS furniture_orders
    FROM
      records
    GROUP BY
      order_date
  )
select
  order_date,
  furniture_orders as furniture,
  round(((furniture_orders) / (total_orders) * 100), 2) as furniture_pct
from
  calc
where total_orders >= 10
  and
  (furniture_orders * 100) / total_orders >= 40
order by 3 desc, 1

 

์ •๋‹ต ์ฝ”๋“œ

with
  calc as (
    SELECT
      order_date,
      COUNT(distinct order_id) AS total_orders,
      COUNT(distinct
        CASE
          WHEN category = 'Furniture' THEN order_id
          ELSE null
        END
      ) AS furniture_orders
    FROM
      records
    GROUP BY
      order_date
  )
select
  order_date,
  furniture_orders as furniture,
  round(((furniture_orders + 0.00) / (total_orders + 0.00) * 100), 2) as furniture_pct
from
  calc
where total_orders >= 10
  and
  (furniture_orders * 100) / total_orders >= 40
order by 3 desc, 1

 

 

ํ•ต์‹ฌ ์š”์ง€

1. ๊ณ ์œ ํ•œ order_id๋กœ ์ฃผ๋ฌธ ์ˆ˜๋ฅผ ์„ธ์•ผ ํ•œ๋‹ค.

 

๊ฐ™์€ order_id๋กœ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ฃผ๋ฌธ record๊ฐ€ ์กด์žฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— distinct order_id๋กœ ์ฃผ๋ฌธ ์ˆ˜๋ฅผ ์„ธ์•ผ ํ•œ๋‹ค.

 

2. SQLite๋Š” ๋‚˜๋ˆ—์…ˆ์„ ํ•  ์‹œ, ์ •์ˆ˜๋กœ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค

 

์ •์ˆ˜๋ฅผ ๋‚˜๋ˆ„๊ธฐํ•˜๋ฉด ์ •์ˆ˜๋กœ ๋‚˜์˜ค๊ธฐ ๋•Œ๋ฌธ์— floatํ˜•์œผ๋กœ ๋งŒ๋“ค์–ด์ฃผ๊ธฐ ์œ„ํ•ด ( + 0.00 )์„ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

 


 

๋А๋‚€ ์ 

๋‹ค๋ฅธ ๋ถ„๋“ค์˜ ์ฝ”๋“œ ๋‹ต์•ˆ์„ ๋ดค์„ ๋•Œ, ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๋” ๊น”๋”ํ•˜๊ฒŒ ํ‘ผ ๊ฒƒ๋“ค๋„ ๋ดค์œผ๋‚˜

๋‚˜๋Š” with ์ ˆ๋กœ ๊ตฌ๋ถ„ํ•ด์„œ ์ฟผ๋ฆฌ ์งœ๋Š” ๊ฑธ ์„ ํ˜ธํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์œ„์˜ ๋‹ต์•ˆ๋Œ€๋กœ ์ž‘์„ฑ์„ ํ–ˆ๋‹ค.

๊ทผ๋ฐ with ์ ˆ์„ ์‚ฌ์šฉํ•˜๋ฉด ํ™•์‹คํžˆ ์ฟผ๋ฆฌ ์งœ๋Š” ๋ฐ ์‹œ๊ฐ„์ด ๋งŽ์ด ์†Œ๋ชจ๋˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

์ข€ ๋” ๊น”๋”ํ•˜๊ฒŒ ํšจ์œจ์ ์œผ๋กœ ์งœ๋Š” ๋ฐฉ๋ฒ•์„ ์ƒ๊ฐํ•ด๋ด์•ผ๊ฒ ๋‹ค.

 

select order_date,
count(distinct(case when category='Furniture' then order_id end)) as furniture,
round((count(distinct(case when category='Furniture' then order_id end))+0.00) / (count(distinct(order_id))+0.00)*100,2) as furniture_pct
from records
group by order_date
having count(distinct order_id) >= 10
and furniture_pct>= 40
order by furniture_pct desc;

^ ๊ฐ€์žฅ ๊น”๋”ํ•œ ์ฝ”๋“œ ๋‹ต์•ˆ์ธ ๋“ฏ

 

https://milkyspace.tistory.com/90

 

[solvesql] ๊ฐ€๊ตฌ ํŒ๋งค์˜ ๋น„์ค‘์ด ๋†’์•˜๋˜ ๋‚  ์ฐพ๊ธฐ

https://solvesql.com/problems/day-of-furniture/ solvesql © Copyright 2021-2022 solvesql.com solvesql.com ๋ฌธ์ œ๋Š” ์œ„์™€ ๊ฐ™๋‹ค. ๊ฐ€๊ตฌ๊ฐ€ ํŒ”๋ฆฐ ์ˆ˜์™€ ๋น„์œจ์„ ๊ตฌํ•ด์ฃผ๋ฉด๋˜๋Š”๋ฐ sqlite๋ฅผ ๋งŽ์ด ์•ˆ์จ๋ด์„œ ๋ชฐ๋ž๋‹ค. ๋‚˜๋ˆ„๊ธฐ๋ฅผ ํ•˜๋ฉด ์ •์ˆ˜

milkyspace.tistory.com

^ ์—ฌ๊ธฐ์„œ ํผ์™”๋‹ค !