sql - 为每个记录增加一个变量
问题描述
我有这个查询:
#create table #tmp_table( n_progressive int , name char(10),
id_numeric(11,0) )
declare @i int = 0 declare @c int declare n_progressive int = 0
declare @var_table table ( name char(10), id_number numeric(11,0) )
insert into @var_table( name, id_number ) select name,id_number from MainTable
select @c= count (*) from @var_table
while(@i<@c) begin set @n_progressive = @n_progressive + 1
insert into #Tmptable( n_progressive , name , id_numeric ) select @n_progressive ,name,id_numeric from @var_table
end
var_table 中的记录是 4。对于每条记录,我希望 n_progressive 增加 +1。
上面查询的结果是这样的:
+--------------+----------+------------+
|n_progressive | name | numeric_id |
+--------------+----------+------------+
|1 | RM1 | 1 |
|1 | RM2 | 2 |
|1 | RM3 | 3 |
|1 | RM4 | 4 |
|2 | RM1 | 1 |
|2 | RM2 | 2 |
|2 | RM3 | 3 |
|2 | RM4 | 4 |
|3 | RM1 | 1 |
|3 | RM2 | 2 |
|3 | RM3 | 3 |
|3 | RM4 | 4 |
|4 | RM1 | 1 |
|4 | RM2 | 2 |
|4 | RM3 | 3 |
|4 | RM4 | 4 |
+--------------+----------+------------+
我想要的是这个:
+---------------+----------+-------------+
|n_progressive | name | numeric_id |
+---------------+----------+-------------+
|1 | RM1 | 1 |
|2 | RM2 | 2 |
|3 | RM3 | 3 |
|4 | RM4 | 4 |
+---------------+----------+-------------+
我不想使用光标。
解决方案
您正在从@var_table
循环的每次迭代中选择所有记录,这就是为什么您将所有记录乘以 4(中的记录数@var_table
)。
但是,您根本不需要循环,并且无论如何在使用 SQL 时都应该努力避免循环,因为 SQL 最适用于基于集合的方法而不是过程方法(有关更多信息,请阅读RBAR:' Row By Agonizing Row'</a> 和RBAR 是什么?如何避免?)
row_number()
您可以简单地使用窗口函数来获取值,而不是循环n_progressive
:
insert into #Tmptable( n_progressive, name, id_numeric)
select row_number() over(order by name), name, id_numeric
from @var_table
推荐阅读
- powerbi - Power BI 根据切片器选择计算 MAX
- javascript - (JavaScript) 如何在three.js 中操作球体的顶点?
- r - 删除R中数据框中列表中<4位数字的数字
- swift - 如何通过在 Swift 中滚动滑块来滚动 UICollectionView?
- c# - 如何使用组合框更改 datagridview 表?
- python - Python MultiLevel Index on DataFrame. Access first row of first index level to apply function
- android - 无法显示,作为 android 软键盘中的小数分隔符
- machine-learning - 迁移学习和元学习之间的差异
- python - 错误:由于环境错误而无法安装软件包:[Errno 28] 设备上没有剩余空间
- batch-file - 在 NotePad++ 中从其父目录运行批处理文件