条件WHERE条件SQL脚本

时间:2016-01-08 08:41:34

标签: sql sql-server select sum where-clause

我需要在进行求和时过滤特定行。表结构和数据如下。 enter image description here

我希望除行[Gain/Lost]以外的所有行的WHERE [Reason] = 'Order Placed' AND [No Of Month Old] = 1列值为SUM。

以下案例值为-560。

4 个答案:

答案 0 :(得分:3)

你用英语很好地描述了你的条件 - 现在你只需要在SQL中编写相同的东西:

SELECT SUM([Gain/Lost]
FROM   mytable
WHERE  NOT ([Reason] = 'Order Placed' AND [No Of Month Old] = 1)

答案 1 :(得分:2)

select userid, sum([Gain/Lost])
from tablename
where [Reason] <> 'Order Placed'
   or [No Of Month Old] <> 1
group by userid

答案 2 :(得分:1)

SELECT UserID,
       SUM(CASE WHEN [Reason] = 'Order Placed' AND [No Of Month Old] = 1
                THEN 0
                ELSE [Gain/Lost]
            END)
FROM tt
GROUP BY UserID

答案 3 :(得分:1)

SELECT SUM([GAIN/LOST]) as 'Gain/Lost'
FROM YourTable yt
WHERE REASON <> 'Order Placed' AND [No of Month Old] <> 1
GROUP BY UserID