Pergunta

I have a number of items that are for rent in an item table. I have a transnational table that shows the rental history on each item in my item table. If the item is currently not being rented then all entries in the "Availability Status" column will say 'closed'. If the item is being rented one of the fields in the "Availability Status" column will say "ONRENT". I want to write a query that will list each rental item and return whether they are currently "ONRENT" (Not Available) or "CLOSED" (Available). I have written a query that returns rental items that are "ONRENT" since my WHERE clause can find the only row containing "ONRENT". Not sure how to return available items when all the rows in the "Availability Status" column say "CLOSED" Here is my successful query for ONRENT items.

select      rl.[No_],
        rl.[Manufacturer Code],
        rl.[Model Code],
        rl.[Availability Status],
        rl.[Start Date],
        rh.[Order Date],
        rh.[No_],
        rh.[Ship-to Name],
        rh.[Ship-to Address]

from        [LIVE$Rental Line]rl left outer join [LIVE$Rental Header]rh 
on rl.[Document No_] = rh.[No_]
where       rl.[Availability Status] = 'ONRENT'
and         rl.[No_] not like 'SR%'
Foi útil?

Solução

I simplified your use case a little, for sake of clarity. What you seem to be looking for is something like this:

SELECT distinct no, 'CLOSED' FROM table1 t1
WHERE EXISTS (SELECT * FROM table1 WHERE status = 'CLOSED' AND no = t1.no)
UNION
SELECT distinct no, 'OPEN' FROM table1 t2
WHERE NOT EXISTS (SELECT * FROM table1 WHERE status = 'CLOSED' AND no = t2.no) 

I should add there are many ways to solve this problem, some of which may be more efficient than this one.

Outras dicas

if you simply switch your join,

SELECT
            rl.[No_],
            rl.[Manufacturer Code],
            rl.[Model Code],
            COALESCE(rl.[Availability Status], 'CLOSED') [Availability Status],
            rl.[Start Date],
            rh.[Order Date],
            rh.[No_],
            rh.[Ship-to Name],
            rh.[Ship-to Address]
    FROM
            [LIVE$Rental Header] rh
        LEFT OUTER JOIN
            [LIVE$Rental Line] rl  
                ON
                        rl.[Document No_] = rh.[No_]
                    AND
                        rl.[Availability Status] = 'ONRENT'
    WHERE
            rl.[No_] not like 'SR%';

Then you'll get all the [LIVE$Rental Header], you'll only get [LIVE$Rental Line] data for related rows that are 'ONRENT', as well as your other conditions.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top