与SQL中的数量偏移

时间:2017-03-18 07:38:17

标签: mysql sql

让我们假设我们有以下表格

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

我们如何知道SQL中第401项的项目编号? (答案应该是product_id:3)。查询应返回product_id

让我们假设行已按顺序

3 个答案:

答案 0 :(得分:2)

您可以使用相关查询查找累计和,然后使用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

您也可以使用用户变量:

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

答案 1 :(得分:2)

如果是ORACLE,则无法使用SQLServer

这是通过使用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

答案 2 :(得分:0)

您可以通过获取累积总和来对变量执行此操作。然而,古尔夫的答案太复杂了。

我认为这是最简单的方法:

|word 234:1 |tag 12:1 |word 123:1 |tag 10:1 |word 123:1 |tag 13:1
|word 234:1 |tag 12:1 |word 123:1 |tag 10:1