SQL Server中的自定义ID列

时间:2016-03-21 10:13:38

标签: sql-server

我有这张桌子:

ID      ORDER   SCNID   SCANNER
-------------------------------
170842  85986   20      APL-1   
170843  85986   20      APL-1   
170844  85986   20      APL-1   
170845  85986   20      APL-1   
170886  86004   200     GPL-2   
170897  86011   1600    MAP-1   
170900  86011   1600    MAP-1   
170903  86011   1600    MAP-1   
170904  86011   1600    MAP-1   
170906  86011   1600    MAP-1   
170908  86011   1600    MAP-1   
170909  86011   1600    MAP-1   
170918  86024   520     NIX-3   
170922  86028   1050    OPL-3   
170923  86029   1050    OPL-3   

我需要创建一个customorderID列,它看起来像这样:

ID      ORDER   SCNID   SCANNER  CUSORDERID
--------------------------------------------
170842  85986   20      APL-1    85986-1
170843  85986   20      APL-1    85986-2
170844  85986   20      APL-1    85986-3
170845  85986   20      APL-1    85986-4
170886  86004   200     GPL-2    86004-1
170897  86011   1600    MAP-1    86011-1
170900  85986   1600    MAP-1    85986-5
170903  86011   1600    MAP-1    86011-2
170904  86011   1600    MAP-1    86011-3
170906  86011   1600    MAP-1    86011-4
170908  86011   1600    MAP-1    86011-5
170909  86011   1600    MAP-1    86011-6
170918  86024   520     NIX-3    86024-1
170922  86028   1050    OPL-3    86028-1
170923  86029   1050    OPL-3    86029-1    

行按ID&和根据ID,特定ORDER(例如86011)自定义ORDERID的第1条记录将是86011-1,如果该ORDER的任何其他记录则为86011-2,依此类推。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

with tempOrder as
(
   select ID,[ORDER],SCNID,Scanner, ROW_NUMBER() over (partition by [ORDER] order by [ORDER], ID) as OrderNum
   from OrderTable   
)
Select Id,[Order],SCNID,Scanner, Str([ORDER]) +'-'+ Str(OrderNum) as CUSORDERID from tempOrder
order by [ORDER]