Calculated fields within SQL query

为君一笑 提交于 2020-01-06 14:10:26

问题


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:


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



来源:https://stackoverflow.com/questions/30177740/calculated-fields-within-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!