【问题标题】:Compare Grand total of "Group by subtotals" in SQL Server比较 SQL Server 中“按小计分组”的总计
【发布时间】:2015-04-24 18:01:12
【问题描述】:

我有下表形式的数据。我在 Quantity(MG) 的最后一列应用了 sum 的聚合函数。

ITEM         STORE     Quantity(MG) 

Rice Bags     ABC      150 
Sugar Bags    ABC      200
Rice Bags     NEW      50 
Sugar Bags    New      20 
Rice Bags     Alpha    25 

我的 Select SQL 看起来像这样。

Select ITEM, STORE, SUM(Quantity(MG)
From....
.........
.........
Group by ITEM, STORE 
Having SUM(Quantity(MG) > 50 

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

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

【问题讨论】:

  • 阅读窗口集over Partition by...它们允许您创建内联聚合总计。然后可以将其与其他聚合进行比较,而不会对基本聚合产生负面影响。真的很酷。
  • GROUP BY GROUPING SETS((),()) 也可能是一个选项。

标签: sql sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012


【解决方案1】:

sum() over(partition by) 将为您完成这项工作:

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

已编辑:

select ITEM, STORE,Quantity(MG),grp_sum from 
     (Select ITEM, STORE,Quantity(MG), SUM(Quantity(MG)) over(partition by item,store) as grp_sum
        From table)temp
        where grp_sum< 50

【讨论】:

  • 这会将 Quantity 列中的所有值更改为总计。我不希望对当前显示在行中的小计进行任何更改。我只想要另一个命令来过滤掉总和小于 50 的记录。
  • where子句中的窗口函数?
【解决方案2】:

您需要在Quantity(MG) 上应用组总和:

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 

【讨论】:

  • 谢谢dnoeth,我会试一试
【解决方案3】:

我想这就是你想要的:

;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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2016-04-20
    • 1970-01-01
    相关资源
    最近更新 更多