SQL给有相同列的 数据添加一个递增的编号

参考于:https://zhidao.baidu.com/question/229402549.html

1、表中有自增列row:

select (select count(*) from table1 where [user]=t1.[user] and row>=t1.row) as id,[user] from table1 as t1

order by [user],id

2、表中没有自增列,但有其它列,其中有一列可以区分开每一行数据,假设为utime:

select (select count(*) from table1 where [user]=t1.[user] and utime>=t1.utime) as id,[user] from table1 as t1

order by [user],id

实际运用:

SELECT AP.ArticlePurchaseID 物品id,AP.ArticleTypeID 类别id,[ArticleTypeName] 类别名称,
AT.[ArticleTypeName]+'-'+CAST((select count(*) from [t_ArticlePurchase] where ArticleTypeID=AP.ArticleTypeID and ArticlePurchaseID<=AP.ArticlePurchaseID) AS varchar(MAX)) 物品名称
FROM t_ArticlePurchase AP 
LEFT JOIN t_ArticleType AT ON AT.ArticleTypeID = AP.ArticleTypeID
WHERE AP.IsValid=1
ORDER BY AP.ArticleTypeID ASC,AP.ArticlePurchaseID asc

主要是这句:

ISNULL(ArticleName,[ArticleTypeName]+'-'+CAST((select count(*) from [t_ArticlePurchase] where ArticleTypeID=AP.ArticleTypeID and ArticlePurchaseID<=AP.ArticlePurchaseID) AS varchar(MAX)))物品名称,

实际效果:

说明:

根据类别的名称,给物品命名,格式是:类别名称+'-'+自增的编号

还可以用来修复数据:

UPDATE  AP
SET [ArticleName]=AT.[ArticleTypeName]+'-'+CAST((select count(*) from [t_ArticlePurchase] where ArticleTypeID=AP.ArticleTypeID and ArticlePurchaseID<=AP.ArticlePurchaseID) AS varchar(MAX))
FROM  [t_ArticlePurchase] AP 
LEFT JOIN t_ArticleType AT
ON AT.ArticleTypeID = AP.ArticleTypeID
WHERE AP.IsValid=1;

 随手记:

SELECT b.InventoryName, b.InventoryName+CAST((select count(*) from [t_FixedAssetsItems] where CID=a.CID and FID<=a.FID) AS varchar(MAX))
FROM [dbo].[t_FixedAssetsItems] a
LEFT JOIN t_Inventory AS b ON b.InventoryID=a.CID
ORDER BY a.FID ASC,a.CID asc
UPDATE a SET a.FName= b.InventoryName+CAST((select count(*) from [t_FixedAssetsItems] where CID=a.CID and FID<=a.FID) AS varchar(50))
FROM [T_FixedAssetsItems] a
LEFT JOIN t_Inventory AS b ON b.InventoryID=a.CID;  

UPDATE a SET a.InventoryName=b.InventoryName+CAST((select count(*) from [T_StorageInfo] where InventoryID=a.InventoryID and FID<=a.FID) AS varchar(50))
FROM [T_StorageInfo] a
LEFT JOIN t_Inventory AS b ON b.InventoryID=a.InventoryID;

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值