Mysql SUM基于另一个计算的字段条件

时间:2013-01-30 03:59:56

标签: mysql sql aggregate-functions

有三个表Users,Lists,Details。这是我的表格结构和数据样本

userid username   |  list_id  list_val  user_id  |   detail_id   list_id   multipler
1      user1      |     1       500        1     |      1           1         3
2      user2      |     2       300        1     |      2           1         2
3      user3      |     3       600        1     |      3           2         1
                        4       100        2            4           2         1
                                                        5           3         4

SELECT
users.username,
SUM(lists.lists_var),
FROM
users
INNER JOIN lists ON users.userid = lists.user_id
GROUP BY
users.username
HAVING
(SELECT (exp(sum(log(COALESCE(details.multipler, 1))))) FROM details WHERE
details.list_id = lists.list_id) > 3

此查询为我提供了结果

user1 - 1400

但我想要一些IF multipler_total> 3那么SUM(list_val)所以结果必须是:

user1 - 1100

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
users.username,
SUM(lists.lists_var),
FROM
users
INNER JOIN lists ON users.userid = lists.user_id
INNER JOIN (SELECT list_id, SUM(multiplier) mult_total FROM details GROUP BY list_id) d
ON d.list_id = lists.list_id and d.mult_total > 3
GROUP BY
users.username