一个SQL汇总了不同的“分组”级别

时间:2016-03-23 10:30:44

标签: c# sql winforms db2 ibm-midrange

我在数据库中有一个Stock表:

enter image description here

基于Stock Table中的数据,我想要输出更详细的数据:

enter image description here

库存数量表示项目A的库存总量。

位置数量表示每个位置的项目A的总数量

子位置数量表示项目A的总数量,表示每个子位置的特定位置。

我想知道是否有办法在一个查询中获取详细输出,或者我应该单独进行每个查询并编写一些代码以在每个结果之间进行连接。

我可以写:

  • 为了获得股票数量:

    SELECT Item, Sum(Qty) as StockQty
    From Stock
    Group By Item;
    
  • 为了获得位置数量:

    SELECT Item, Location, Sum(Qty) as LocationQty
    From Stock
    Group By Item, Location;
    
  • 为了获得子位置数量:

    SELECT Item, Location, SubLocation, Sum(Qty) as SubLocationQty
    From Stock
    Group By Item, Location, SubLocation;
    

然后在代码后面,在datagridview中为输出编写一些代码。

实际上,我正在寻找一个查询,它返回一个数据表中的所有数据并将其绑定到datagridview。

欢迎任何其他解决方案。

我在AS400工作,但如果其他DBMS中有解决方案,请回答,我会尝试在我的DBMS环境中使其工作(如果可能)。

3 个答案:

答案 0 :(得分:4)

试试这个:

SELECT t3.Item, t3.StockQty,
       t2.Location, t2.LocationQty,
       t1.SubLocation, t1.SubLocationQty
FROM (
   SELECT Item, Location, SubLocation, Sum(Qty) as SubLocationQty
   From Stock
   Group By Item, Location, SubLocation) AS t1
JOIN (
   SELECT Item, Location, Sum(Qty) as LocationQty
   From Stock
   Group By Item, Location
) AS t2 ON t1.Item = t2.Item AND t1.Location = t2.Location
JOIN (
   SELECT Item, Sum(Qty) as StockQty
   From Stock
   Group By Item
) AS t3 ON t1.Item = t3.Item 

答案 1 :(得分:4)

怎么样:

SELECT Item, Location, SubLocation, Sum(Qty) as SubLocationQty 
From Stock 
Group By Item, Location, SubLocation with rollup

如果你的rdbms中有汇总,那真的很简单。只需用字符串'Total'替换'null',你就可以免费使用.....

答案 2 :(得分:0)

您可以为此使用多个子查询。

SELECT Item, 
(SELECT StockQty 
 FROM (SELECT Item, Sum(Qty) AS StockQty
       FROM Stock
       GROUP BY Item)) AS StockQty
(SELECT LocationQty 
 FROM (SELECT Item, Location, Sum(Qty) AS LocationQty
       FROM Stock
       GROUP BY Item, Location)) AS LocationQty,
(SELECT SubLocationQty 
 FROM (SELECT Item, Location, SubLocation, Sum(Qty) AS SubLocationQty
       FROM Stock
       GROUP BY Item, Location, SubLocation)) AS SubLocationQty
FROM Stock