mysql - 如何使用 ORDER BY 计算行数直到某个值

标签 mysql

我需要使用 ORDER BY 获取某些行的计数。

如何获取行数 orderId = 50 之前是什么 (我看到答案是3,但我需要mysql查询如何得到它)

我有这样的 mysql 查询:

select c.id as customerId, o.id as orderId from orders o
inner join customers c on (c.id=o.customerId)
order by c.id asc, o.id desc

此查询输出:

customerId   orderId
19           36
19           35
19           34
31           50     
31           49
31           48
53           73
53           72

最佳答案

<强> SQL DEMO

SELECT Max(rn)
FROM (
    select customerId, 
           orderId , 
           @row := if( orderid = 50, 
                        null,
                        @row + 1 ) as rn
    from orders o
    cross join ( SELECT @row := 0 ) as vars
    order by customerId asc, orderId  desc
)  t

是否可以使用row_number

SELECT MIN(rn) - 1 as cnt
FROM (
    select customerId, 
           orderId , 
           row_number() over (order by customerId asc, orderId  desc ) as rn
    from orders
) t
WHERE orderId = 50;

关于mysql - 如何使用 ORDER BY 计算行数直到某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210074/

相关文章:

php - 我收到 SQL 错误,试图将表单插入数据库

mysql - mysql中出现重复记录

php - MySQL 和 PHP - 使用 'LIKE' 和 'NOT LIKE'

mysql - 错误代码 1005 - 无法创建表

php echo json_encode from DB entries -> 获取奇怪的格式。如何获得正确的 JSON

WordPress 帖子页面上的 MYSQL SQL 语法错误

mysql - MySQL数据导入错误

mysql - 即使连接丢失,是否也可以保留表锁?

php - 匹配并查找数据库中数组中的所有值

MySQL查找多个表中多种产品的最低价格