SQL中需要基于列信息的序列号

时间:2013-03-26 07:14:00

标签: sql sql-server-2000

我的表中有几列(SQL Server 2000数据库)。我有像

这样的信息
OrderID      Design        Qty
------------------------------    
28500   R6192WHM+DWN    1
28500   P3150WHM+DWN    1
28504   E3085/2DWN  1
28503   R5595HCT(P) 1
28503   R4768DWN    1
28505   E3415D(P)   1
28505   E3413DWN    1
28505   E3365AQ(P)  1

我需要这样的信息(即基于orderid的sno)

OrderID   Design        Qty    SNO
-------------------------------------    
28500   R6192WHM+DWN    1       1
28500   P3150WHM+DWN    1       2
28504   E3085/2DWN  1       1
28503   R5595HCT(P) 1       1
28503   R4768DWN    1       2 
28505   E3415D(P)   1       1
28505   E3413DWN    1       2
28505   E3365AQ(P)  1       3

2 个答案:

答案 0 :(得分:1)

试试这个

select t1.*, SNO = count(*)
  from Table1 t1
  join Table1 t2
    on t1.OrderID = t2.OrderID
   and t1.Design >= t2.Design
 group by t1.OrderID, t1.Design, t1.Qty
 order by t1.OrderID, t1.Design

答案 1 :(得分:0)

尝试,它适用于MS Sql server 2005及以上版本:

select 
    *, 
    row_number() over (partition by OrderID order by OrderID) 
from YourTable

样品

select 
    *, 
    row_number() over (partition by OrderID order by OrderID) 
from(
    select 28500 OrderID,   'R6192WHM+DWN' Design,  1 Qty union
    select 28500 OrderID,   'P3150WHM+DWN' Design,  1 Qty union
    select 28504 OrderID,   'E3085/2DWN' Design,    1 Qty union
    select 28503 OrderID,   'R5595HCT(P)' Design,   1 Qty union
    select 28503 OrderID,   'R4768DWN' Design,      1 Qty union
    select 28505 OrderID,   'E3415D(P)' Design,     1 Qty union
    select 28505 OrderID,   'E3413DWN' Design,      1 Qty union
    select 28505 OrderID,   'E3365AQ(P)' Design,    1 Qty
)x

请尝试以下查询,该查询适用于sql server 2000 select *, (select count(*) from YourTable t2 where t2.OrderId=t1.OrderID and t2.Design<t1.Design)+1 as SNo From YourTable t1 order by OrderID, Design