问题
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:
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.
来源:https://stackoverflow.com/questions/41691832/adding-subquery-to-a-grid-query