SELECT Date(o."updatedAt"), c.name -> c."defaultLang" as name, SUM(o.amount) as amount,…
- User
SELECT Date(o."updatedAt"), c.name -> c."defaultLang" as name, SUM(o.amount) as amount, SUM(o.price) as total_price, o.currency FROM "Order" o LEFT JOIN "Pack" p ON o."packId" = p.id LEFT JOIN "Collection" c ON p."collectionId" = c.id WHERE o.status IS TRUE GROUP BY Date(o."updatedAt"), p.id, c.id, o.currency ORDER BY Date(o."updatedAt") DESC
currency를 그룹화하지 않고, {currency: SUM(price), ...} 로 total_price에 담고 싶어. Postgres 16버전에서 해당 sql로 고쳐줘.최적화도 해줘 JSONB_OBJECT_AGG는 WITH로 따로 쿼리를 빼줘
- Assistant
PostgreSQL 16 버전에서는 SQL 쿼리의 유연성과 기능이 크게 향상되었습니다. 요구사항에 맞추어 화폐별 총 가격을 JSON 객체로 집계하기 위해, 주어진 쿼리를 개선한 다음과 같은 버전으로 제공할 수 있습니다. 이를 위해
JSONB_OBJECT_AGG함수를 활용하고, 성능 최적화를 위해 WITH 구문 (Common Table Expression, CTE)을 사용하는 것이 좋습니다.최적화된 쿼리:
WITH currency_totals AS ( SELECT Date(o."updatedAt") AS updated_date, c.id AS collection_id, o.currency, SUM(o.price) AS total_price FROM "Order" o LEFT JOIN "Pack" p ON o."packId" = p.id LEFT JOIN "Collection" c ON p."collectionId" = c.id WHERE o.status IS TRUE GROUP BY updated_date, p.id, c.id, o.currency ) SELECT ct.updated_date, c.name -> c."defaultLang" AS name, SUM(o.amount) AS amount, JSONB_OBJECT_AGG(ct.currency, ct.total_price) AS total_price FROM currency_totals ct JOIN "Order" o ON Date(o."updatedAt") = ct.updated_date LEFT JOIN "Pack" p ON o."packId" = p.id LEFT JOIN "Collection" c ON p."collectionId" = ct.collection_id GROUP BY ct.updated_date, ct.collection_id ORDER BY ct.updated_date DESC;