如何在SQL中基于其他列减小值

时间:2016-04-02 21:53:15

标签: sql sql-server tsql

我有下表:

ID_Client | Counter | Length | Amount | Date_From | Date_To
-------------------------------------------------------------
AAA         0         25       30      2015-01-09   2015-01-15
AAA         2         25       30      2015-01-15   2015-02-06  
AAA         2         25       30      2015-02-06   2015-03-10
AAA         1         25       30      2015-03-10   2015-04-12 
AAA         1         25       30
AAA         2         25       30
AAA         1         25       30
AAA         1         25       30
AAA         1         25       30
AAA         2         25       30      2016-04-01   9999-99-99 Infinity (last record for AAA at the moment)
BBB         0         30       60
BBB         1         30       60
BBB         2         30       60
BBB         2         30       60

Value1列:

Value1的第1行= Counter的第1行

Value1的第2行= Value1的第1行+计数器列的第2行等。

Value2列:

Value2的第1行=金额的第1行

Value2的第2行= Value2的第1行 - 计数器列的第2行等

结果应按ID_Client分组。当新客户端时,Value1和Value2应该再次开始计数。

我需要得到这张表:

ID_Client | Counter | Length | Amount | Value1 | Value2
--------------------------------------------------------
AAA         0         25       30       0        30
AAA         2         25       30       2        28
AAA         2         25       30       4        26
AAA         1         25       30       5        25
AAA         1         25       30       6        24
AAA         2         25       30       8        22
AAA         1         25       30       9        21
AAA         1         25       30       10       20
AAA         1         25       30       11       19
AAA         2         25       30       13       17
BBB         0         30       60       0        60
BBB         1         30       60       1        59 
BBB         2         30       60       3        57
BBB         2         30       60       5        55

由于

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

我指定行号,因为我需要一个唯一的值来排序,然后我们只需将value1加起来并从value1中减去或多或少的数量..

这使用公用表表达式来创建一个带有行号的结果集,然后创建一个分析函数(窗口集)来生成“运行”总数。

if((dogs+cats)!=population) System.out.println(**error message about wrong input**);

现在我们有一个排序日期我不再需要行号了......

with cte as (
  Select ID_CLIent, Counter, Length, Amount, row_number()  
  over (partition by ID_CLient order by counter) RN
from foo)

Select ID_Client
     , Counter
     , Length
     , Amount
     , sum(Counter) over (Partition by ID_CLIENT order by ID_Client, RN) as Value1
     , Amount - sum(Counter) over (Partition by ID_CLIENT order by ID_Client, RN) as Value2 
  from cte c
  order by ID_Client