Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较SQL Server中“按小计分组”的总计_Sql_Sql Server_Sql Server 2008_Sql Server 2008 R2_Sql Server 2012 - Fatal编程技术网

比较SQL Server中“按小计分组”的总计

比较SQL Server中“按小计分组”的总计,sql,sql-server,sql-server-2008,sql-server-2008-r2,sql-server-2012,Sql,Sql Server,Sql Server 2008,Sql Server 2008 R2,Sql Server 2012,我有下表形式的数据。我在QuantityMG的最后一列应用了一个求和的聚合函数 ITEM STORE Quantity(MG) Rice Bags ABC 150 Sugar Bags ABC 200 Rice Bags NEW 50 Sugar Bags New 20 Rice Bags Alpha 25 我的selectsql如下所示 Select ITEM, STORE,

我有下表形式的数据。我在QuantityMG的最后一列应用了一个求和的聚合函数

ITEM         STORE     Quantity(MG) 

Rice Bags     ABC      150 
Sugar Bags    ABC      200
Rice Bags     NEW      50 
Sugar Bags    New      20 
Rice Bags     Alpha    25 
我的selectsql如下所示

Select ITEM, STORE, SUM(Quantity(MG)
From....
.........
.........
Group by ITEM, STORE 
Having SUM(Quantity(MG) > 50 
我面临的问题是,有一个语句,我希望SQL比较给定项目(比如米袋)的所有数量值的总和,即150+50+25=225。但是对于上面的查询,它并没有像预期的那样工作。当我应用SUMQuantityMG>50的条件时,它实际上将值50与每个唯一行进行比较,并跳过米袋数量小于50的行,在本例中为第5行。理想情况下,不应跳过该行,因为米袋数量的总和为225,因此不应跳过米袋的任何行


通过设置将此过滤器应用于此组的解决方案是什么

sum overpartition by将为您完成这项工作:

Select ITEM, STORE, SUM(Quantity(MG)) over(partition by item,store) as sm
From table
where Quantity(MG)< 50
编辑:


我想这就是你想要的:

;with cte as(select item, store, quantity, sum(quantity) over(partition by item) as groupedQuantity)
select item, store, sum(quantity) as quantity
from cte
where groupedQuantity > 50
group by item, store

您需要在QuantityMG上应用组和:


读取分区上的窗口集。。。它们允许您创建内联聚合总计。然后可以将其与其他聚合进行比较,而不会对基本聚合产生负面影响。真的很酷。按分组集分组也可能是一个选项。这会将“数量”列中的所有值更改为总计。我不希望对当前显示在行中的小计进行任何更改。我只需要另一个命令,它可以过滤出总和小于50的记录。where子句中的窗口函数?谢谢dnoeth,我将尝试一下
;with cte as(select item, store, quantity, sum(quantity) over(partition by item) as groupedQuantity)
select item, store, sum(quantity) as quantity
from cte
where groupedQuantity > 50
group by item, store
select ITEM, STORE, sumQuantity
from
 (
   Select ITEM, STORE, SUM(Quantity) as sumQuantity
      ,SUM(SUM(quantity)) OVER (PARTITION BY ITEM) as groupSum 
   From....
   .........
   .........
   Group by ITEM, STORE
 ) as dt
where groupSum > 50