2017-08-02 54 views
0

数量作为参数,因此我只能将记录提取至@quantity。我在FROM之后尝试的内容没有那么有意义,所以下面给出了我的查询,我需要实现该条件。我尝试都在WHERE和使用HAVING但无法:提取记录不大于提供的数量

SELECT prod_id, 
    product, 
    technology, 
    price, 
    quantity 
FROM tbl_product 
------SUM(quantity) <= @quantity 

示例数据:

prod_id product technology price quantity 
1  M1  ST   25.33 10 
2  M2  ST   23.65 50 
3  S1  ST   54.32 90 
4  S2  PY   21.435 30 
5  S3  PY   98.64 110 

IF @Quantity = 150个然后第一3个记录应被取出。

+1

您可以添加一些示例数据以使问题更清晰吗? –

+0

什么是输入和输出? – Steven

回答

2

你需要得到一个累积和(基于你的问题中的“提取到”),这是使用窗口函数最有效地完成的。

尝试:

with cumulative as (
    SELECT prod_id, 
     product, 
     technology, 
     price, 
     quantity, 
     sum(quantity) over (order by <order column>) as cumulative_quantity 
    FROM tbl_product 
) 
select 
    prod_id, 
    product, 
    technology, 
    price, 
    quantity 
from cumulative where cumulative_quantity <= @quantity; 

您需要提供订单列,表示你要累积相加用什么顺序。

所以当@Quantity = 150,你的结果将是:

prod_id product technology price quantity 
1  M1  ST   25.33 10 
2  M2  ST   23.65 50 
3  S1  ST   54.32 90 

(如果你使用PROD_ID由列的顺序)。

+0

感谢您的快速响应,但它没有给出预期的结果。 – Susang

+0

这是返回前三行是正确的,但在最后一行数量是150,因为我们有90实际。但是我在''中使用了'prod_id'' – Susang

+0

尝试使用上面编辑的代码。如果您有任何问题,请告诉我。 –

0

假设你要取前N个记录被prod_id的累积总和为有序小于@quantity,那么你可以尝试以下查询:

SELECT 
    prod_id, 
    product, 
    technology, 
    price, 
    quantity 
FROM tbl_product t1 
WHERE (SELECT SUM(t2.quantity) FROM tbl_product t2 
     WHERE t2.prod_id <= t1.prod_id) < @quantity 
0

基于产品,你可以找到如下

SELECT distinct prod_id, 
     product, 
     technology, 
     price, 
FROM tbl_product 
where product in (
SELECT product 
FROM tbl_product 
GROUP BY product 
HAVING SUM(quantity) <= @quantity)