Calculated fields within SQL query

2019-09-17 07:51发布

Invalid column name ItemA, ItemB, ItemC, ItemD, and ItemE

I am migrating this from Progress to SQL and can't reference the calculated fields within the query. After researching the error it appears the only solution is to replace each item with the full expression or create a nested select statement. Neither seem to work in this case.

SELECT  
    OrderQty - (ItemE + ShippedQty) AS ItemA, 

    ((CASE WHEN (ItemA > ItemB AND ItemA > 0) 
        THEN (ItemA - ItemB) 
        ELSE 0 
    END)) AS ItemC, 

    UnitPrice * ItemC AS ItemD, 

    ((CASE WHEN OnHandQty > (ReservedQty + PickingQty) 
        THEN OnHandQty - (ReservedQty + PickingQty) 
        ELSE 0 
    END)) AS ItemB, 

    ((CASE WHEN ReservedQty > - 1 
        THEN (ReservedQty + PickedQty + PickingQty) 
        ELSE 0 
    END)) AS ItemE, 


-- Example of enumerated expression that is far to confusing to continue.
SELECT
    OrderQty - (((CASE WHEN ReservedQty > -1 THEN (ReservedQty + PickedQty + PickingQty) ELSE 0 END)) + ShippedQty),
    ((CASE WHEN (OrderQty - ((CASE WHEN ReservedQty > -1 THEN (ReservedQty + PickedQty + PickingQty) ELSE 0 END)) > 
        ((CASE WHEN OnHandQty > (ReservedQty + PickingQty) THEN OnHandQty - (ReservedQty + PickingQty) ELSE 0 END)) AND
        (OrderQty - (ItemE + ShippedQty) > 0) THEN (OrderQty - (ItemE + ShippedQty) ELSE 0 END)))), 
    UnitPrice * ((CASE WHEN (ItemA > ItemB AND ItemA > 0) THEN (ItemA - ItemB) ELSE 0 END))...

1条回答
贪生不怕死
2楼-- · 2019-09-17 08:21

In case you are migrating to SQL Server, you can use CROSS APPLY clauses to create aliases for each one of the calculated fields:

SELECT  
    x.ItemA,     
    t.ItemC,     
    UnitPrice * t.ItemC AS ItemD,     
    y.ItemB,     
    z.ItemE
FROM mytable
CROSS APPLY (SELECT CASE WHEN ReservedQty > - 1 
                            THEN (ReservedQty + PickedQty + PickingQty) 
                         ELSE 0 
                    END) z(ItemE)
CROSS APPLY (SELECT OrderQty - (ItemE + ShippedQty)) x(ItemA)
CROSS APPLY (SELECT CASE WHEN OnHandQty > (ReservedQty + PickingQty) 
                            THEN OnHandQty - (ReservedQty + PickingQty) 
                         ELSE 0 
                    END) y(ItemB)
CROSS APPLY (SELECT CASE WHEN (x.ItemA > y.ItemB AND x.ItemA > 0) 
                            THEN (x.ItemA - y.ItemB) 
                         ELSE 0 
                    END) AS t(ItemC) 

SQLFiddle Demo

查看更多
登录 后发表回答