Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One SQL to summarize different 'group by' levels

I have a Stock table in database:

enter image description here

Based on data in Stock Table, I want to have as output more detailed data:

enter image description here

Stock Qty represents the total qty in stock for Item A.

Location Qty represents the total qty for Item A for each Location

Sub Location Qty represents the total qty for Item A, for a specific location for each sub Location.

I was wondering if there is a way to get the detailed output in one query or should I make each query individually and write some code to join between each results.

I could write:

  • In order to get Stock Qty:

    SELECT Item, Sum(Qty) as StockQty
    From Stock
    Group By Item;
    
  • In order to get Location Qty:

    SELECT Item, Location, Sum(Qty) as LocationQty
    From Stock
    Group By Item, Location;
    
  • In order to get Sub Location Qty:

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

And then in code behind, write some code for output in a datagridview.

Actually, I am looking for a query that returns all the data in one datatable and bind it to the datagridview.

Any other solution is welcome.

I am working in AS400 but if there is a solution in others DBMS, please answered, I will try to make it work (if possible) in my DBMS environment.

like image 276
ehh Avatar asked Feb 08 '23 10:02

ehh


2 Answers

Try this:

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 
like image 137
Giorgos Betsos Avatar answered Feb 10 '23 00:02

Giorgos Betsos


how about :

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

if you have rollup in your rdbms it is really simple. just replace the 'null' you get with the string 'Total' and you're homefree.....

like image 42
Zahiro Mor Avatar answered Feb 10 '23 01:02

Zahiro Mor