我如何分别显示每个客户国家/地区的国内订单和非国内订单的订单总额和数量?

How i can show sums and count of orders for domestic orders and non domastic orders separetly for each customers country?

我有 2 个请求,想将它们组合成 5 列,例如 Country_name - count_of_orders_for_domestic - sums_for_domectic - count_of_orders_for_non_domestic - sums_for_non_domestic

国内订单金额统计

SELECT co.name country,
       count(cu.id) domestic_orders,
       sum(o.price) domastic_sum
FROM countries co
JOIN cities c ON co.id=c.country_id
JOIN customers cu ON c.id=cu.city_id
JOIN orders o ON cu.id=o.customer_id
JOIN products AS p ON o.product_id=p.id
WHERE p.country_id=co.id
GROUP BY co.name

非国内订单数量和金额

SELECT co1.name country,
       count(cu1.id) non_domestic_orders,
       sum(o1.price) non_domastic_sum
FROM countries co1
JOIN cities c1 ON co1.id=c1.country_id
JOIN customers cu1 ON c1.id=cu1.city_id
JOIN orders o1 ON cu1.id=o1.customer_id
JOIN products AS p1 ON o1.product_id=p1.id
WHERE p1.country_id<>co1.id
GROUP BY co1.name

我尝试使用 Union,但它有 3 列,我看不出国内和非国内的区别。然后我尝试创建一个新别名,但我在计数和求和运算方面遇到了问题。

您可以使用过滤聚合:

SELECT co.name as country,
       count(cu.id) filter (where p.country_id = co.id) as domestic_orders,
       sum(o.price) filter (where p.country_id = co.id) as domastic_sum,
       count(cu.id) filter (where p.country_id <> co.id) as non_domestic_orders,
       sum(o.price) filter (where p.country_id <> co.id) as non_domastic_sum
FROM countries co
  JOIN cities c ON co.id=c.country_id
  JOIN customers cu ON c.id=cu.city_id
  JOIN orders o ON cu.id=o.customer_id
  JOIN products AS p ON o.product_id=p.id
GROUP BY co.name