[英]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我需要实现的逻辑是
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.