条件乘以和和列

时间:2016-01-27 14:18:25

标签: sql tsql if-statement

我想得到一个列的总和,但我遇到了条件

的问题
|  Target  |  MultiOnQry  |   
---------------------------
|  50393   |       1      |
|  49      |       1      |
|  303     |       0      |
|  1934    |       1      |
|  45      |       0      |
---------------------------

我想对目标列中的截断值求和,但如果MultiOnQry = 1,则希望乘以X. 这是从vba调用的,所以我将用X代替标量。

SELECT SUM(CAST(Target*X AS Integer)) AS TargetSum FROM table WHERE ID = 1078

2 个答案:

答案 0 :(得分:2)

 SELECT SUM(CASE WHEN MultiOnQry = 0 
        then CAST(Target AS Integer)
         else CAST(Target AS Integer)*X end) AS TargetSum
 FROM table WHERE ID = 1078

试试这个。

答案 1 :(得分:0)

尝试:

SELECT SUM(IIF(MultiOnQry = 1, CAST(Target AS INT)*X, CAST(Target AS INT))) AS TargetSum
FROM table WHERE ID = 1078