write-query 스킬 2회차: 클로드가 쓴 SQL과 실행 결과

가상 향초 쇼핑몰 '달빛향방' 주문 DB · 클로드 코드 · 소넷 5.5 · 생각 깊이 중간

카테고리별.sql

-- 2026년 10월 카테고리별 순매출 / 주문 건수 (SQLite)
-- 순매출 = 주문 금액(qty * unit_price) - 해당 주문 항목의 환불액 (환불 시점이 11월이어도 차감)
-- 제외: 취소 주문, 테스트 계정
WITH oct_items AS (
    -- 10월 주문의 상품 라인. 2026-11-01 00:00:00 주문이 섞이지 않도록 반개구간 사용
    SELECT
        o.id          AS order_id,
        oi.product_id,
        oi.qty * oi.unit_price AS item_amount
    FROM orders o
    JOIN customers c    ON c.id = o.customer_id
    JOIN order_items oi ON oi.order_id = o.id
    WHERE o.ordered_at >= '2026-10-01'
      AND o.ordered_at <  '2026-11-01'
      AND o.status <> 'cancelled'
      AND c.is_test = 0
),
item_sales AS (
    -- (주문, 상품) 단위로 먼저 합산: 환불과 조인할 때 행이 중복(fan-out)되지 않게 함
    SELECT order_id, product_id, SUM(item_amount) AS item_amount
    FROM oct_items
    GROUP BY order_id, product_id
),
item_refunds AS (
    -- 환불 시점과 무관하게 모두 반영 (refunded_at 필터 없음)
    SELECT order_id, product_id, SUM(amount) AS refund_amount
    FROM refunds
    GROUP BY order_id, product_id
)
SELECT
    COALESCE(p.category, '미분류')                       AS category,
    SUM(s.item_amount - COALESCE(r.refund_amount, 0))    AS net_sales,
    COUNT(DISTINCT s.order_id)                           AS order_count
FROM item_sales s
JOIN products p ON p.id = s.product_id
LEFT JOIN item_refunds r
       ON r.order_id = s.order_id AND r.product_id = s.product_id
GROUP BY COALESCE(p.category, '미분류')
ORDER BY net_sales DESC;

재구매.sql

-- 2026년 10월 중 주문을 2번 이상 한 고객 수 (SQLite)
-- 제외: 취소 주문, 테스트 계정
SELECT COUNT(*) AS repeat_customers
FROM (
    SELECT o.customer_id
    FROM orders o
    JOIN customers c ON c.id = o.customer_id
    WHERE o.ordered_at >= '2026-10-01'
      AND o.ordered_at <  '2026-11-01'
      AND o.status <> 'cancelled'
      AND c.is_test = 0
    GROUP BY o.customer_id
    HAVING COUNT(*) >= 2
);

직접 실행한 결과 (sqlite3)

categorynet_salesorder_count
디퓨저752,00026
선물세트630,00011
향초397,50016
미분류69,0002

순매출: 정답과 같음

repeat_customers
15

재구매 고객: 정답과 같음