SQL 自动计数器取决于列值
SQL autocounter depending on a column value
我正在尝试创建一个序列号之类的东西,它在每一行上逐行迭代,并在列 shopID 更改时重置。但是我想用一个变量。
select
@Counter --what to do here?
,@data as Data
,case
when (ShopID.N.value('.', 'decimal(5,0)') = -1) then NULL
else ShopID.N.value('.', 'decimal(5,0)')
end as ShopID
from @xmlRes.nodes('/Root/ResponseData/response/shopItems') as S(N)
outer apply S.N.nodes('recordNumber') as ShopID(N)
我需要这样的东西:
Counter | Data | ShopID
--------------------------------------
1 | Sample | 1
2 | Sample | 1
3 | Sample | 1
1 | Sample | 2
2 | Sample | 2
3 | Sample | 2
4 | Sample | 2
1 | Sample | 3
select
ROW_NUMBER() OVER (PARTITION BY ShopID ORDER BY Data) as Counter,
,@data as Data
,case
when (ShopID.N.value('.', 'decimal(5,0)') = -1) then NULL
else ShopID.N.value('.', 'decimal(5,0)')
end as ShopID
from @xmlRes.nodes('/Root/ResponseData/response/shopItems') as S(N)
outer apply S.N.nodes('recordNumber') as ShopID(N)
row_number() over (partition by ShopID)
如果您希望按特定顺序分配序列号,还应在分区依据后添加一个 order by 子句。
我正在尝试创建一个序列号之类的东西,它在每一行上逐行迭代,并在列 shopID 更改时重置。但是我想用一个变量。
select
@Counter --what to do here?
,@data as Data
,case
when (ShopID.N.value('.', 'decimal(5,0)') = -1) then NULL
else ShopID.N.value('.', 'decimal(5,0)')
end as ShopID
from @xmlRes.nodes('/Root/ResponseData/response/shopItems') as S(N)
outer apply S.N.nodes('recordNumber') as ShopID(N)
我需要这样的东西:
Counter | Data | ShopID
--------------------------------------
1 | Sample | 1
2 | Sample | 1
3 | Sample | 1
1 | Sample | 2
2 | Sample | 2
3 | Sample | 2
4 | Sample | 2
1 | Sample | 3
select
ROW_NUMBER() OVER (PARTITION BY ShopID ORDER BY Data) as Counter,
,@data as Data
,case
when (ShopID.N.value('.', 'decimal(5,0)') = -1) then NULL
else ShopID.N.value('.', 'decimal(5,0)')
end as ShopID
from @xmlRes.nodes('/Root/ResponseData/response/shopItems') as S(N)
outer apply S.N.nodes('recordNumber') as ShopID(N)
row_number() over (partition by ShopID)
如果您希望按特定顺序分配序列号,还应在分区依据后添加一个 order by 子句。