简体   繁体   English

SQL中的数量偏移

[英]Offset with Quantity in SQL

Let us suppose we have following tables 让我们假设我们有下表

product_id | quantity
1          | 250
2          | 150
3          | 120
4          | 300
5          | 301

How do we know that the item number of 401th in SQL? 我们怎么知道SQL中第401项? (the answer should be product_id : 3). (答案应该是product_id:3)。 The query should return the product_id 查询应返回product_id

Let us assume also the row has been in order 让我们假设行也按顺序排列

You can use Correlated query to find cummulative sum and then filter range using between to find the required slot: 您可以使用“相关查询”来查找累计和,然后使用between过滤范围来查找所需的广告位:

select product_id
from (
    select a.*,
        coalesce((
                select sum(quantity)
                from your_table b
                where b.product_id < a.product_id
                ), 0) + 1 cquant1,
        (
            select sum(quantity)
            from your_table b
            where b.product_id <= a.product_id
            ) cquant2
    from your_table a
    ) t
where 401 between cquant1 and cquant2;

Demo 演示

You can also use user variable for this: 您还可以为此使用用户变量:

select *
from (
    select product_id,
        @sum1 := @sum1 + coalesce((
                select quantity
                from your_table x
                where x.product_id < t.product_id
                order by x.product_id desc limit 1
                ), 0) as cquantity1,
        @sum2 := @sum2 + quantity as cquantity2
    from your_table t,
        (select @sum1 := 0, @sum2 := 0) t2
    order by product_id
    ) t
where 401 between cquantity1 and cquantity2;

Demo 演示

In case of ORACLE , this will not work with SQLServer 如果是ORACLE ,则不适用于SQLServer

This is by using LAG and SUM OVER() functions, 这是通过使用LAG和SUM OVER()函数,

SELECT PRODUCT_ID FROM 
(
  SELECT PRODUCT_ID 
    , LAG(CUM_QUAN, 1, 0) OVER (ORDER BY PRODUCT_ID) AS START_QUAN
    , CUM_QUAN END_QUAN
  FROM 
  ( 
    SELECT PRODUCT_ID
      , QUANTITY
      , SUM(QUANTITY) OVER (ORDER BY PRODUCT_ID) AS CUM_QUAN 
    FROM YOUR_TABLE
  )
) WHERE 401 BETWEEN START_QUAN AND END_QUAN

You can do this with variables by getting a cumulative sum. 您可以通过获取累计和来使用变量来执行此操作。 However, Gurv's answer is way too complicated. 但是,古尔夫的答案太复杂了。

I think this is the simplest way: 我认为这是最简单的方法:

select t.*
from (select t.*, (@s := @s + quantity) as running_quantity
      from t cross join
           (select @s := 0) params
      order by product_id
     ) t
where 401 < running_quantity and
      401 >= running_quantity - quantity;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM