Adding subquery to a grid query

蹲街弑〆低调 提交于 2019-12-13 07:04:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!