SQL - 减法行

时间:2016-09-09 11:04:12

标签: sql row subtraction

我有以下查询

SELECT VALUE
    ,Source1
    ,Source2
    ,DocNo
FROM myTable

它返回以下数据:

enter image description here

我想根据以下条件计算减法:

for DocNo A1
if(Source1=1 and Source2=0) VALUE 34
if(Source1=1 and Source2=0) VALUE 21
subtraction  two row 34 - 21 = 13 

有什么想法吗?

预期结果:

enter image description here

2 个答案:

答案 0 :(得分:1)

如果我理解您的问题,请按以下查询:

SELECT Value, Score1, Score2, DocNo
FROM TestTable 
WHERE Score1 = 0

UNION 

SELECT MAX(Value) - MIN(Value) AS Value, 1, 1, DocNo
FROM TestTable 
WHERE Score1 = 1
GROUP BY DocNo
ORDER BY DocNo, Score1

DEMO 也是如此。

答案 1 :(得分:0)

如果您使用的是QL server 2012或更高版本,则可以使用LEAD()函数。

size[0].predator=0;  // Technically not needed because .resize()
size[0].prey1=0;     // will have initialized it to zero anyway
size[0].prey2=0;     // *BUT* explicit is always better than implicit.

// Initialize each element of size to be one greater than previous.
for(int k = 1; k < N; ++k){
  size[k].predator = size[k-1].predator + 1;
  size[k].prey1    = size[k-1].prey1    + 1;
  size[k].prey2    = size[k-1].prey2    + 1;;
}

输出:

enter image description here