简体   繁体   English

如何在 MSSQL 中建立 2 个字段相互依赖的查询

[英]How to build query where 2 fields are inter dependent in MSSQL

I am new to the world of SQL queries, I am comfortable writing basic sql queries limited to to CRUD operations.我是 SQL 查询世界的新手,我很乐意编写仅限于 CRUD 操作的基本 sql 查询。 I am now working on a project where I have to write complex queries and I am seeking help on how to do it.我现在正在从事一个项目,我必须编写复杂的查询,并且正在寻求有关如何执行此操作的帮助。

Scenario I have a table x场景我有一张桌子 x

The logic I need to implement is我需要实现的逻辑是

  1. The first record starts with some default value let us say 0 as StartCount.第一条记录以一些默认值开始,让我们说 0 作为 StartCount。
  2. I need to add numbers Add1+Add2 and deduct Minus我需要添加数字 Add1+Add2 并减去 Minus
  3. The result of step 2+StartCount becomes my EndCount step 2+StartCount 的结果变成了我的 EndCount
  4. The next Month StartCount is the EndCount of the previous row. Next Month StartCount 是上一行的 EndCount。
  5. I have to repeat step 2,3,4 for all the rows in the table.我必须对表中的所有行重复步骤 2、3、4。

How can I do this using SQL如何使用 SQL 做到这一点

You want a cumulative sum, is available using window/analytic functions.您想要一个累积和,可以使用窗口/分析函数。 It is something like this:它是这样的:

select x.*,
       (first_value(startcount) over (order by <ordercol>) +
        sum(add1 + add2 - minus) over (order by <ordercol>)
       ) as yourvalue
from x;

<ordercol> is needed because SQL tables represent unordered sets. <ordercol>是必需的,因为 SQL 表表示无序集。 You need a column that specifies the ordering of the rows.您需要一列来指定行的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM