在SQL中对临时列执行数学运算

时间:2011-08-19 03:15:36

标签: mysql sql

我想要做的就是让我在表中的id上出现,然后根据出现的数量,将另一列的值除以该值。这是查询,以更好地说明我正在尝试做什么。

SELECT t.t_id, count(DISTINCT tm.tm_id) AS occurances, t.value/occurances AS newValue
FROM table t
INNER JOIN table_map tm ON t.t_id = tm.tm_id
GROUP BY tm.tm_id
HAVING occurances > 1

对于那些熟悉SQl的人来说,这不会起作用。然而,我不知道如何让它执行我需要的,或者如果可能的话。我尝试在select中做一个select,但是无法弄清楚如何让它来执行我需要的操作。

正在MySQL 5 DB上执行sql

2 个答案:

答案 0 :(得分:2)

也许你的意思是这样的:

SELECT
  t.t_id,
  t.occurrences,
  t.value / tm.occurrences AS newValue
FROM table t
  INNER JOIN (
    SELECT
      tm_id,
      COUNT(*) AS occurrences
    FROM table_map
    GROUP BY tm_id
    HAVING COUNT(*) > 1
  ) tm ON t.t_id = tm.tm_id

答案 1 :(得分:0)

将其抛入子查询并在此之后进行数学运算:

SELECT t_id, occurances, value/occurances AS newValue
from (
    SELECT t.t_id, count(DISTINCT tm.tm_id) AS occurances, t.value
    FROM table t
    INNER JOIN table_map tm ON t.t_id = tm.tm_id
    GROUP BY t.t_id
    HAVING occurances > 1) t