问题
I have a set of numbers in a two column table, but I need only negative numbers subtracted by 10 and then be able to use them in a query straight after in SQLite3.
I currently have the following query:
10 * (customer_x / 10), 10 * (customer_y / 10),
COUNT (*) FROM t_customer
GROUP BY customer_x / 10, customer_y / 10
ORDER BY 3 DESC;
Which makes the values in customer_x and customer_y into fundamental co-ordinates, but any negative values will be 10 higher then the grid square they should be. I need a way to subtract 10 from only the negative values prior to submitting it into the query.
回答1:
One option would be to use a subquery which generates the adjusted numbers in case of negative values:
SELECT 10 * (t.customer_x / 10) AS col1,
10 * (t.customer_y / 10) AS col2,
COUNT(*) AS some_count
FROM
(
SELECT 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
) t
GROUP BY t.customer_x / 10,
t.customer_y / 10
ORDER BY 3 DESC;
来源:https://stackoverflow.com/questions/41610929/subtract-from-negative-numbers-in-column-to-use-in-sql-query