查询内部的计算

时间:2013-06-03 15:57:20

标签: mysql

SELECT a.id, a.username, a.email, a.created, b.user_id, 
    SUM( (b.price >500) +100 ) + SUM( b.price ) AS gr, SUM( b.price ) AS pris,
     b.created, c.user_id, c.referrer_id, c.created, d.id, d.beginner, d.winner_id
FROM users a, accounts b, referrals c, product d
WHERE a.created
BETWEEN  '2013-05-01'
AND  '2013-05-31'
AND a.id = b.user_id
AND a.id = c.user_id
AND d.beginner !=  '1'
AND d.winner_id = a.id
GROUP BY c.referrer_id
ORDER BY  `pris` ASC 
LIMIT 0 , 3

我已经制定了这个查询。我想解决的问题是

SUM(( b.price >500) +100) + SUM( b.price ) AS gr

我想要计算,如果一个ID的总价格在一个月内超过500,那么它就会增加100.我不确切地知道如何计算此查询中一个人的总价并添加100如果一个月内计数超过500?

3 个答案:

答案 0 :(得分:1)

您可以在此使用CASE声明

SUM( CASE WHEN b.price >500 THEN b.price+100 ELSE b.price END) as gr

答案 1 :(得分:0)

在您的查询中尝试此操作。

SUM(if(b.price >500,100,0))

答案 2 :(得分:0)

糟糕。只是重新阅读你的问题。

一个身份证的总价格:

sum(b.price)

测试一个ID的总价格是否> 500,如果超过500,则加100:

sum(b.price) + case when sum(b.price) >500 then 100 else 0 end as gr