T-SQL:如何计算总值

时间:2010-02-10 13:09:32

标签: sql-server tsql

我正在尝试在T-SQL中执行计算,但我遇到了一些问题。 这是我正在尝试做的事情:

DECLARE @CNT money
SELECT @CNT = 0

Select Amount,
        case
            when Service like 'pay_in' then SET @CNT = @CNT + Amount
            when Service like 'pay_out' then SET @CNT= @CNT - Amount
        end
   from Payment where isActive = 1

select @CNT

由于我对T-SQL语法知之甚少,我被困在这里,如果有人能够把我推向正确的方向,我将非常感激。谢谢!

3 个答案:

答案 0 :(得分:5)

SQL最适合基于集合的方法。尽量不要通过迭代数据集来解决问题,而是通过聚合来解决问题。

DECLARE @CNT money

SELECT 
  @CNT = SUM(
    CASE Service 
      WHEN 'pay_in'  THEN Amount
      WHEN 'pay_out' THEN -1 * Amount
      ELSE 0
    END
  )
FROM
  Payment 
WHERE
  isActive = 1

SELECT @CNT

答案 1 :(得分:4)

您可以在不使用变量的情况下进一步简化:

Select Sum(Case Service
           When 'pay_in' Then Amount
           When 'pay_out' Then -Amount
           End) as Total
From Payment 
Where isActive = 1

答案 2 :(得分:1)

SET内不需要SELECT。尝试:

set @CNT = 0

select 
   @CNT = case
        when Service like 'pay_in' then @CNT + Amount
        when Service like 'pay_out' then @CNT - Amount
    end
from Payment 
where isActive = 1

或者,没有变量:

 Select 
    sum(case
        when Service like 'pay_in' then Amount
        when Service like 'pay_out' then -Amount
    end) as Total
 from Payment 
 where isActive = 1