如何在MySQL中汇总生成的列?

时间:2011-02-11 14:56:55

标签: mysql

此查询工作正常,它会生成一个名为“total_each”的列,我只想对该列中的所有值进行求和并显示它们。

我认为这是一件非常简单的事情,但我找不到合适的写作方式,我已经到处寻找。

select ((datediff(date1, date2))*daily_cost) as total_each
from table1, table2, table3 
where bid = fk1_bid 
AND vid = fk2_vid 
AND bid = 2;

我认为底线是我不知道如何为生成的列应用SUM函数。

2 个答案:

答案 0 :(得分:3)

select sum(total_each) from (select ((datediff(date1, date2))*daily_cost) as total_each
from table1, table2, table3 
where bid = fk1_bid 
AND vid = fk2_vid 
AND bid = 2)

答案 1 :(得分:3)

您在列表达式上调用SUM:

SELECT SUM((DATEDIFF(date1, date2))*daily_cost) AS total_each
  FROM table1, table2, table3 
 WHERE bid = fk1_bid 
   AND vid = fk2_vid 
   AND bid = 2;

我建议您使用JOIN表示法。我们无法确切知道如何使用JOIN重写您的查询,因为我们不知道哪个列属于哪个表,但它可能看起来像:

SELECT SUM((DATEDIFF(t1.date1, t2.date2))*t3.daily_cost) AS total_each
  FROM table1 AS t1
  JOIN table2 AS t2 ON t1.bid = t2.fk1_bid
  JOIN table3 AS t3 ON t1.vid = t3.fk2_vid
 WHERE t1.bid = 2;