MySQL:连续订单持仓

发布于 2024-11-04 17:44:34 字数 666 浏览 0 评论 0原文

使用 MySQL 我需要使用 ORDER BY 用列表中的位置填充列。

我看到了这个帖子: mysql-get-row-position-in-order-by

上述帖子(第二个解决方案)的问题在于,当它在列表中遇到相同的值时,位置是相同的,但下一条记录会出现“间隙”。我希望这些位置是连续的。

假设我有一个像这样的列表:

   id   val
    A    3
    B    5 
    C    2
    D    6
    E    1
    F    8
    G    2
    H    6

我想获得带有这样的位置列的有序输出:

   id   val        pos
    E    1          1
    C    2          2
    G    2          2
    A    3          3
    B    5          4
    D    6          5
    H    6          5 
    F    8          6

using MySQL I need to fill a column with the position in the list using ORDER BY.

I saw this post :
mysql-get-row-position-in-order-by

The problem with the above post (2nd solution), is that it, when it encounters the same values in the list, the position is the same, but 'gaps' appear for the next record(s). I want the positions to be consecutive.

Let's say I have a list like this :

   id   val
    A    3
    B    5 
    C    2
    D    6
    E    1
    F    8
    G    2
    H    6

I would like to get an ordered output with a position column like this :

   id   val        pos
    E    1          1
    C    2          2
    G    2          2
    A    3          3
    B    5          4
    D    6          5
    H    6          5 
    F    8          6

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凝望流年 2024-11-11 17:44:34
select id,val,
@pos := if(@prev<>val,@pos+1,@pos) as pos,
@prev := val as val
from table,(select @pos:=0,@prev:='') as r order by val 

我同意其他建议,即最好在应用程序级别执行此操作。

select id,val,
@pos := if(@prev<>val,@pos+1,@pos) as pos,
@prev := val as val
from table,(select @pos:=0,@prev:='') as r order by val 

I agree with other advices that it would be better to do this at application level.

睫毛溺水了 2024-11-11 17:44:34

这个怎么样:

  SELECT `id`,
         (SELECT COUNT(DISTINCT `val`) + 1
            FROM `table`
           WHERE `val` < `outer`.`val`) AS `pos`,
         `val`
    FROM `table` `outer`
ORDER BY `val`

刚刚从那个线程中获取了我的答案并做了一些修改。

但正如 @reko_t 在评论中提到的 - 我个人投票支持用编程语言来做这件事。

What about this:

  SELECT `id`,
         (SELECT COUNT(DISTINCT `val`) + 1
            FROM `table`
           WHERE `val` < `outer`.`val`) AS `pos`,
         `val`
    FROM `table` `outer`
ORDER BY `val`

Just've taken my answer from that thread and changed it a little.

But as @reko_t mentioned in the comments - I personally vote for doing this in programming language.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文