简体   繁体   中英

SQL Join table with calculated fields

I want to add another column to this query to show backorders that need to be processed.

Currently the table is showing all orders that have outstanding items and the in stock amount for each stock ref included.

I want to to add a field for suggested invoice amount. Ie if the order qty is 5 , the invoice qty is 2 and the in stock qty is 2 then suggest to deliver 2.

if the instock amount was 100 then suggest to deliver 3.

My current attempt is below but I cant work out how to do the last bit.

I know i need to do (qtyOrdered-qtyinvoiced) but literally hit a brick wall.

SELECT 
    c.cus_name,
    ol.orderLines_stockRef,
    ol.orderLines_qtyOrdered,
    ol.orderlines_qtyInvoiced,
    pr.products_instock
FROM
    cus c
        JOIN
    orderheader oh ON oh.orderHeader_customer = c.cus_id
        JOIN
    orderlines ol ON ol.orderLines_orderId = oh.orderHeader_id
        JOIN
    products pr ON ol.orderlines_stockref = pr.products_reference
WHERE
    ol.orderLines_qtyOrdered <> ol.orderlines_qtyInvoiced

Current output :

输出

Try this:

SELECT 
    c.cus_name,
    ol.orderLines_stockRef,
    ol.orderLines_qtyOrdered,
    ol.orderlines_qtyInvoiced,
    pr.products_instock,
    (CASE WHEN ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced > pr.products_instock
          THEN pr.products_instock
          ELSE ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced) AS qtyToSend,
FROM
    cus c
        JOIN
    orderheader oh ON oh.orderHeader_customer = c.cus_id
        JOIN
    orderlines ol ON ol.orderLines_orderId = oh.orderHeader_id
        JOIN
    products pr ON ol.orderlines_stockref = pr.products_reference
WHERE
    ol.orderLines_qtyOrdered <> ol.orderlines_qtyInvoiced

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