简体   繁体   中英

SQL How to create a case statement to pull sum qtys based on the largest unit of measure

I am new to SQL and trying to create a report for the warehouse to let them know the total of largest units of each item that is inbound so they can prepare warehouse space.

The largest unit for Pen and Pencil is Case and Paper is Pallet. How would i create a case statement to sum and filter by the largest unit?

There are two tables: The "Units" table has all the items with their units based on the base unit. The "Orders" table has the open orders with the qtys ordered.

SELECT O.item, O.unit, sum(O.ordered) 

FROM Orders as O
LEFT JOIN Unit as U on U.item = I.item


Item  Unit    Ordered Order No.
----- ----    ------- ---------
Pen    Each   200     50012
Pen    Each   400     50018
Pen    Case   1       50051
Pencil Each   50      50108
Pencil Case   2       50185
Paper  Case   10      50186
Paper  Sheet  240000  50187
Paper  Case   40      50188

Item   Unit  Unit Size
-----  ----  --------
Pen    Each   1
Pen    Box    20
Pen    Case   200
Pencil Each   1
Pencil Box    10
Pencil Case   50
Paper  Sheet  1
Paper  Ream   300
Paper  Case   6000
Paper  Pallet 120000

OUTCOME

Item   Unit   Quantity
----   ----   -------- 
Pen    Case   4
Pencil Case   3
Paper  Pallet 2

You query needs a GROUP BY :

SELECT O.item, O.unit, SUM(O.ordered) 
FROM Orders O LEFT JOIN
     Unit U 
     ON U.item = I.item
GROUP BY O.item, O.unit;

This returns the units that have been ordered . I'm not 100% sure that is what you really want, although it makes sense to me.

Don't think you're looking for a case statement, but an interesting join. This works in postgres, row_number() syntax may be different in your flavor of SQL.

You need to join into the unit table twice. Once to see how many base units the order has. Second time to look at only the largest sized unit for each product.

Run the subquery to see row level data, or the whole to get it aggregated by item.

select item, preferred_unit, sum(qty_largest_units)
from (
select
    o.item, 
    o.unit, 
    o.order_qty, 
    u.unit_size, 
    o.order_qty*u.unit_size as qty_smallest_units,
    largest_tbl.unit, 
    largest_tbl.unit_size as preferred_unit,
    o.order_qty*u.unit_size/largest_tbl.unit_size as qty_largest_units
from orders o
left join unit u
    on u.item = o.item and o.unit = u.unit
left join (
    select
        item,
        unit,
        unit_size,
        row_number() over (partition by item order by unit_size desc) as rn 
    from unit
) largest_tbl
    on largest_tbl.rn = 1 and largest_tbl.item = o.item
) subquery
group by item, preferred_unit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM