从列中的负数减去以在SQL查询中使用

时间:2017-01-12 10:36:26

标签: sql sqlite subtraction

我在两列表中有一组数字,但我只需要减去10的负数,然后在SQLite3中直接使用它们。

我目前有以下查询:

10 * (customer_x / 10), 10 * (customer_y / 10), 
COUNT (*) FROM t_customer 
GROUP BY customer_x / 10, customer_y / 10 
ORDER BY 3 DESC;

这使得customer_x和customer_y中的值成为基本坐标,但任何负值都将比它们应该的网格平方高10。我需要一种方法在将其提交到查询之前仅从负值中减去10。

1 个答案:

答案 0 :(得分:0)

一种选择是使用子查询,在负值的情况下生成调整后的数字:

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;