开发者

Excluding certain fields from an SQL SUM query

I am using the followin开发者_开发问答g SUM query with SQL

SELECT SUM(cost) as total FROM sales where passport =

How would I exclude certain records from the calculation, for example where paid = 1?


Do you mean like this ?

SELECT SUM(cost) as total FROM sales where (passport = $myPassport AND paid <> 1)


Simply

SELECT SUM(cost) as total 
FROM sales
WHERE passport = ?
 AND paid <> 1

You may also be looking for a group by here

SELECT passport, SUM(cost) as total 
FROM sales
WHERE passport = ?
 AND paid <> 1
GROUP BY passport


SELECT SUM(cost) as total FROM sales where passport = "12345" and paid <> 1


SELECT SUM(cost) as total 
FROM sales 
WHERE passport = 12345
AND paid <> 1


did you mean to get only total that equal to 1 ?

USE : HAVING total = 1


Sometimes it's useful to use IF statements like that:

SELECT COUNT(mct.id), SUM(mct.cost * IF(mct.status = 1, 0, 1))
FROM my_cool_table mct;

In that way when status field equals 1 cost will be multiplied by 0 and excluded from SUM but row will not be excluded for count function.

Another way is to use select inside SUM, but it will be not so useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜