选择总和(金额)作为总计条件

时间:2014-02-18 13:31:27

标签: mysql sql

我想让总交易量超过50000的用户

SELECT   sum(tractions.amount) as total , user_id  FROM `tractions` where `total` > 50000   group by user_id

我收到此错误

#1054 - Unknown column 'total' in 'where clause'
诅咒表中没有总列,但我应该怎么写这个条件?

4 个答案:

答案 0 :(得分:4)

您需要一个聚合总计的having子句:

SELECT   sum(tractions.amount) as total , user_id 
FROM `tractions`
group by user_id
HAVING total > 50000;

编辑:

如果我正在编写此查询,它将如下所示:

select t.user_id,  sum(t.amount) as total
from tractions t
group by t.user_id
having sum(t.amount) > 50000;

我发现大写的关键词让人分心。我(几乎)总是在一行的开头放置我聚合的字段。我大量使用表别名,它们是表的缩写。我没有转义标识符,因为我从不在标识符中使用保留字或特殊字符。我把表达式放在having子句中因为。 。 。好吧,我认为曾几何时,并非所有数据库都支持在having子句中使用列别名。

答案 1 :(得分:0)

试试这个

SELECT   sum(tractions.amount) as total , user_id  FROM `tractions` where  sum(tractions.amount) > 50000   group by user_id

答案 2 :(得分:0)

SELECT   sum(tractions.amount) as total , user_id  
FROM `tractions` 
where sum(tractions.amount) > 50000   
group by user_id

答案 3 :(得分:0)

SELECT 
    sum(tractions.amount) as total, user_id
FROM
    `tractions`
group by user_id
having total > 50000;