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
postgres에서 사용중인 구문이야. order_amounts AS ( SELECT DATE("createdAt") AS "orderDate", "currency", SUM("price") AS "totalPrice" FROM "Order" WHERE "status" = TRUE GROUP BY DATE("createdAt"), "currency" ), 이걸 이용해서 JSON_OBJECT_AGG("currency", "totalPrice")를 엮어 select에 total_price 대신 넣어줘. 그렇게되면 기존 sql select에서는 currency를 안보여줘도 돼.
- Assistant
기존의 SQL 쿼리를 수정하여
JSON_OBJECT_AGG("currency", "totalPrice")를 사용하여 각 "createdAt" 날짜별로 total_price를 currency별로 집계해 JSON 객체로 표현하려면, 우선 order_amounts라는 서브쿼리를 만들고 이를 메인 쿼리에 사용해야 합니다. 아래 예시는 요청한 사항을 반영하여 수정된 쿼리입니다:WITH order_amounts AS ( SELECT Date(o."updatedAt") AS "orderDate", c.name -> c."defaultLang" as name, o.currency, SUM(o.amount) AS amount, SUM(o.price) AS totalPrice FROM "Order" o JOIN "Pack" p ON o."packId" = p.id JOIN "Collection" c ON p."collectionId" = c.id WHERE o.status IS TRUE GROUP BY Date(o."updatedAt"), p.id, c.id, o.currency ) SELECT oa."orderDate", oa.name, oa.amount, JSON_OBJECT_AGG(oa.currency, oa.totalPrice) AS total_price FROM order_amounts oa GROUP BY oa."orderDate", oa.name, oa.amount ORDER BY oa."orderDate" DESC;이 쿼리는 WITH 절을 사용해
order_amounts라는 이름의 CTE(Common Table Expression)를 정의합니다. 이 CTE는 주문 날짜("orderDate"), 컬렉션 이름(name), 화폐 단위(currency), 주문량(amount), 그리고 각 화폐 단위별 총 가격()을 선택하여 그룹화합니다. 그 후, 최종 SELECT 문에서는 테이블에서 날짜, 이름, 수량별로 그룹화하고, 함수를 사용하여 와 를 JSON 객체로 집계하여 로 반환합니다.