Adding subquery to a grid query

2019-09-10 04:58发布

Following from this question, I have another query that I need to subtract a value of 10 from for all negative numbers in the data. Sadly, I'm just not sure how to implement the same subquery as is given in the previous question.

The query in question is

SELECT 10 * (c.customer_x / 10), 10 * (c.customer_y / 10),
COUNT(*) as num_orders,
SUM(o.order_total)
FROM t_customer c 
JOIN t_order o
ON c.customer_id = o.customer_id
GROUP BY c.customer_x / 10, c.customer_y / 10
ORDER BY SUM(o.order_total) DESC;

which calculates the order totals from each grid square.

1条回答
贪生不怕死
2楼-- · 2019-09-10 05:24

Your original query doesn't change much in the query below. The only difference is the new join and one more term added to the SELECT list:

SELECT 10 * (c.customer_x / 10) AS col1,
       10 * (c.customer_y / 10) AS col2,
       COUNT(*) AS num_orders,
       SUM(o.order_total) AS order_total_sum
FROM
(
    SELECT customer_id,
           CASE WHEN customer_x < 0 THEN customer_x - 10 ELSE customer_x END AS customer_x,
           CASE WHEN customer_y < 0 THEN customer_y - 10 ELSE customer_y END AS customer_y
    FROM t_customer
) c
INNER JOIN t_order o
    ON c.customer_id = o.customer_id
GROUP BY c.customer_x / 10,
         c.customer_y / 10
ORDER BY SUM(o.order_total) DESC

Note that you could solve this without the use of the subquery which I have used. However, the subquery makes it much more readable, and lets us compute the adjusted customer_x and customer_y values neatly.

查看更多
登录 后发表回答