按多个SUM()过滤

时间:2017-06-12 15:57:05

标签: sql-server group-by sum filtering

我需要构建一个通过SUM(函数)返回order_ID过滤的查询。

假设我只需要在“笔”,“铅笔”和“橡皮擦”的总和等于或大于15时过滤下面的数据。换句话说,我需要排除“标记”和“框架”。我想我需要GROUP BY order_ID

order_ID |article_ID | QTY |
---------------------------- 
   1     |  pen      | 5   |
   1     | pencil    | 5   |
   1     | eraser    | 5   |
   1     | stamp     | 3   |
   1     | frames    | 3   |
   2     |  pen      | 3   |
   2     | pencil    | 5   |
   2     | eraser    | 5   |
   3     |  pen      | 5   |
   3     | pencil    | 10  |

我希望只得到order_ID = 1,因为2和3都超出了我的条件。你能帮帮我吗?

3 个答案:

答案 0 :(得分:1)

后聚合过滤应该这样做。

SELECT order_id FROM t 
WHERE article_id IN( "pen", "pencil", "eraser" )
 GROUP BY order_id
HAVING SUM(QTY)>=15

答案 1 :(得分:0)

您可以使用以下条件聚合:

Select order_id from #yourorder group by order_id
having sum(case when article_id in ('pen','pencil','eraser') then qty else 0 end) >= 15 

答案 2 :(得分:0)

根据您的输入,order_id 1&将返回3, NOT 仅order_id 1

  

只有在"笔","铅笔"的总和时和"橡皮擦"等于或大于   超过15

作为下一个演示: -

Create table mytable (order_ID  int , article_ID  varchar(20),QTY int)
insert into mytable values
(1,'pen',5),
(1,'pencil',5),
(1,'eraser',5),
(1,'stamp',3),
(1,'frames',3),
(2,'pen',3),
(2,'pencil',5),
(2,'eraser',5),
(3,'pen',5),
(3,'pencil',10)

select order_ID,sum(QTY) SumQty
from mytable
WHERE article_id IN('pen','pencil','eraser' )
group by order_ID  
having sum(QTY) => 15

<强>输出: -

order_ID    SumQty
  1          15
  3          15