我现在 抽出 一个数据集
店铺号 商品 数据条数 自增列
3 A 3 空
3 B 3 空
3 C 3 空
4 A 2 空
4 F 2 空
5 E 1 空经过怎么样的 处理 才能变成
3 A 3 1
3 B 3 2
3 C 3 3
4 A 2 1
4 F 2 2
5 E 1 1以店铺号 为单位 根据 【数据条数】 对 【自增列】 列 进行 赋值
店铺号 商品 数据条数 自增列
3 A 3 空
3 B 3 空
3 C 3 空
4 A 2 空
4 F 2 空
5 E 1 空经过怎么样的 处理 才能变成
3 A 3 1
3 B 3 2
3 C 3 3
4 A 2 1
4 F 2 2
5 E 1 1以店铺号 为单位 根据 【数据条数】 对 【自增列】 列 进行 赋值
WITH huang
AS ( SELECT 店铺号 ,
商品 ,
数据条数 ,
ROW_NUMBER() OVER ( PARTITION BY 店铺号 ORDER BY GETDATE() ) 自增列
FROM tb
)
UPDATE a
SET A.自增列 = b.自增列
FROM TB a
INNER JOIN huang b ON a.店铺号 = b.店铺号
AND a.商品 = b.商品
AND a.数据条数 = b.数据条数
-- Author :TravyLee(物是人非事事休,欲语泪先流!)
-- Date :2012-11-27 15:59:16
-- Version:-- Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) -- Feb 10 2012 19:13:17 -- Copyright (c) Microsoft Corporation-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)--
----------------------------------------------------------------
--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
go
create table [test]
(
[店铺号] int,
[商品] varchar(1),
[数据条数] int,
[自增列] int
)
insert [test]
select 3,'A',3,null union all
select 3,'B',3,null union all
select 3,'C',3,null union all
select 4,'A',2,null union all
select 4,'F',2,null union all
select 5,'E',1,null
goalter table test
add id int identity(1,1)
go
update test
set [自增列]=(select count(1) from test b where b.id<=test.id and test.店铺号=b.店铺号)
goalter table test
drop column id
select * from test/*
店铺号 商品 数据条数 自增列
3 A 3 1
3 B 3 2
3 C 3 3
4 A 2 1
4 F 2 2
5 E 1 1
*/
as(
select 3,'A',3,null union all
select 3,'B',3,null union all
select 3,'C',3,null union all
select 4,'A',2,null union all
select 4,'F',2,null union all
select 5,'E',1,null)
select 店铺号,商品,数据条数,自增列=row_number()over (partition by 店铺号 order by 商品) from tb