简体   繁体   中英

what is wrong with my sql query (case when exists)

I'm trying to understand how case when exists expression works, there is two tables one is trOrderHeader which stores main info about any order. Other is trOrderLine which stores details about an order and there is a column IsClosed which indicates Order is somehow closed (canceled or completed).

So my query is below which I am trying to get OrderLineID with IsClosed column (I can do it by joins it is easy but I am trying case when exists expression) but all IsClosed column returns 1;

SELECT 
    OrderLineId,
    IsClosed = 
        CASE 
        WHEN EXISTS (select * from trOrderHeader  where IsClosed=1)
        THEN    1 
        WHEN EXISTS (select * from trOrderHeader  where IsClosed=0)
        THEN   0
        END
FROM 
    trOrderLine
GROUP BY OrderLineId

结果

Isn't this supposed to give me if an Order is Closed write 1, if an Order is not Closed write 0?

Did I misunderstand case when exists expression?

You would need to correlate the subqueries. Assuming that column OrderId can be used to relate the tables, then:

SELECT 
    OrderLineId,
    IsClosed = 
        CASE 
        WHEN EXISTS (select 1 from trOrderHeader h where h.IsClosed = 1 AND h.OrderId = l.OrderId)
        THEN    1 
        WHEN EXISTS (select 1 from trOrderHeader h where IsClosed = 0 AND h.OrderId = l.OrderId)
        THEN   0
        END
FROM trOrderLine l
GROUP BY OrderLineId

However, the logic of the query could probably be simplified by using a JOIN and an aggregate function to compute the status. Something like this could be what you need:

SELECT l.OrderLineId, MAX(h.isClosed) IsClosed
FROM trOrderLine l
INNER JOIN trOrderHeader h ON h.OrderId = l.OrderId
GROUP BY l.OrderLineId

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