我需要在表格中添加订单项。这是我所拥有的一个例子(规模小得多):
shiptoid,lineitem
642218,0
642218,0
642218,0
3041340,0
3041077,0
3041077,0
这就是我需要的东西
shiptoid,lineitem
642218,1
642218,2
642218,3
3041340,1
3041077,1
3041077,2
对于每个独特的shiptoid,我需要一个从1开始的递增行项目编号。我过去做过类似的事情,但我不能为我的生活弄明白。
答案 0 :(得分:1)
如果您使用的是SQL Server,则可以使用:
declare @tbl table (shiptoid int)
insert into @tbl values (642218), (642218), (642218), (3041340), (3041077), (3041077)
select shiptoid, row_number() over (partition by shiptoid order by shiptoid) as lineitem from @tbl
以下是它的回报:
shiptoid lineitem
----------- --------------------
642218 1
642218 2
642218 3
3041077 1
3041077 2
3041340 1
答案 1 :(得分:0)
OLD QUERIES
对于SQL Server:
SELECT ROW_NUMBER()
OVER (ORDER BY ShiptoID) AS Row,
ShiptoID
FROM YourShip
对于MYSQL:
SELECT s.shiptoid,
@rownum := @rownum + 1 AS Row
FROM yourship s,
(SELECT @rownum := 0) r
对于Oracle:
SELECT ShiptoID, ROWNUM AS Row,
ShiptoID
FROM YourShip
对于MySQL:* SQLFIDDLE:忽略同一页面中的其他表格。
查询:
select y.shiptoID, y.row
from (select shiptoID,
@row:=if(@x=shiptoID,@row,0) + 1 as row,
@x:=shiptoID
from yourship
order by shiptoID, row asc
)as y
结果:
SHIPTOID ROW
642218 1
642218 2
642218 3
3041077 1
3041077 2
3041340 1
对于Oracle:Oracle有RANK()
,DENSE_RANK()
OVER PARTITION
类似于MYSQL。
因此我们可以在ORACLE中使用与MYSQL类似的查询。但最好的部分是,我在ROWNUM
子句中使用ORDER BY
;)所以说出所有3中最简单的逻辑/语法
参考:* SQLFIDDLE
查询:
SELECT shiptoID,
DENSE_RANK() OVER
(PARTITION BY shiptoID ORDER BY rownum) AS row
FROM yourShip
;
结果:
SHIPTOID ROW
642218 1
642218 2
642218 3
3041077 1
3041077 2
3041340 1
答案 2 :(得分:0)
您没有提到您的DBMS,因此这是ANSI SQL(适用于大多数现代DBMS):
SELECT shiptoid,
row_number() over (partition by shiptoid) as lineitem
FROM the_table;