How to increase counter in select(如何在选择中增加计数器)
问题描述
我有这种情况-
Column A
1
0
0
0
1
0
0
0
0
1
0
1
0
0
1
0
我想要这样的东西-
Column A Column B
1 1
0 1
0 1
0 1
1 2
0 2
0 2
0 2
0 2
1 3
0 3
1 4
0 4
0 4
1 5
0 5
就像在 A 列中每次出现 1 一样,我们将 B 列中的数字增加一.我想在一个选择中有这个.我不能为此使用循环.
Its like for each occurance of 1 in column A we are increasing the number in column B by one. I want to have this in a select. I can't use loop for this.
我使用的是 SQL-Server 2008 R2.任何人都可以请告诉我它是如何做到的.提前致谢.
I am using SQL-Server 2008 R2. Can anyone please give me idea how it can done. Thanks in advance.
推荐答案
使用 cte 和窗口函数 Row_Number()... 但是,我要注意,最好在 OVER 子句中替换 (Select NULL)具有适当的顺序(即身份 int、日期时间).
With a cte and window function Row_Number()... However, I should note that it would be best if you replace (Select NULL) in the OVER clause with a proper sequence (ie identity int, datetime).
Declare @YourTable table (ColumnA int)
Insert Into @YourTable values (1),(0),(0),(0),(1),(0),(0),(0),(0),(1),(0),(1),(0),(0),(1),(0)
;with cte as (
Select *,RN=Row_Number() over (Order By (Select Null)) from @YourTable
)
Select A.ColumnA
,ColumnB = sum(B.ColumnA)
From cte A
Join cte B on (B.RN<=A.RN)
Group By A.ColumnA,A.RN
Order By A.RN
退货
ColumnA ColumnB
1 1
0 1
0 1
0 1
1 2
0 2
0 2
0 2
0 2
1 3
0 3
1 4
0 4
0 4
1 5
0 5
这篇关于如何在选择中增加计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在选择中增加计数器
- SQL 临时表问题 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
