0

我需要将订单项添加到表格中。这是我所拥有的一个示例(规模要小得多):

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

对于每个唯一的船体,我需要一个从 1 开始的递增行项目编号。我过去做过类似的事情,但我终其一生都无法弄清楚。

4

3 回答 3

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
于 2012-12-07T18:09:19.430 回答
0

旧查询

对于 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

对于甲骨文:

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 的查询。但最好的部分是,我ROWNUMORDER 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
于 2012-12-07T18:18:25.570 回答
0

您没有提到您的 DBMS,所以这是 ANSI SQL(适用于大多数现代 DBMS):

SELECT shiptoid,
       row_number() over (partition by shiptoid) as lineitem
FROM the_table;
于 2012-12-07T19:27:46.457 回答