带条件的 SQL 和

我目前有一个大的 SQL 语句,我添加以下行,以获得每个交易 ID (它是唯一的)的总现金:

select sum(cash) from Table a where a.branch = p.branch
and a.transID = p.transID) TotalCash

现在我需要做同样的事情,但是只需要计算上个月的现金价值,所以我有这样的东西:

select sum(CASE ValueDate WHEN > @startMonthDate THEN cash ELSE NULL END)
from Table a where a.branch = p.branch and a.transID = p.transID) TotalMonthCash

对不起,我没有完整的声明,但它真的很长,具体到存储过程的上下文,但希望有人会知道我的意思?

301123 次浏览

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

Try moving ValueDate:

select sum(CASE
WHEN ValueDate > @startMonthDate THEN cash
ELSE 0
END)
from Table a
where a.branch = p.branch
and a.transID = p.transID

(reformatted for clarity)

You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.

With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.

SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch
AND t1.transID = t2.transID
AND ValueDate > @startMonthDate HAVING money > 0;