Batman Batman - 2 months ago 7
SQL Question

Subtracting the results of two queries

I have a DB with a query telling me how many keys total per specific room and another indicating how many per specific room are currently signed out. I'd like a create a third query indicating how many per room are now available.

Access File: http://jumpshare.com/b/k7pEg4

Query 1 (Keys per room)

SELECT r.room_name, count(r.room_id) AS Key_Count
FROM keys AS k
INNER JOIN rooms AS r ON r.room_id = k.room_id
GROUP BY r.room_id, r.room_name
ORDER BY 2 DESC;


Query 2 (KPR Signedout)

SELECT r.room_name, Count(r.room_id) AS Key_Count
FROM rooms AS r
INNER JOIN (keys AS k
INNER JOIN signin AS s ON k.key_id = s.key_id) ON r.room_id = k.room_id
WHERE (((s.[return_date]) Is Null))
GROUP BY r.room_name, r.room_id
ORDER BY 2 DESC;


This is the result from query 1 and 2. If Room FY218 has 8 total keys and 2 keys currently signed out. Can I combine my queries to tell me this room has 6 keys remaining. If not how can I get this result.

enter image description here

These are my table and relationships:

enter image description here

Answer

This should be what you want:

SELECT r.room_name, Count(k.key_id) AS Key_Count
FROM rooms AS r
INNER JOIN keys AS k ON r.room_id = k.room_id 
WHERE k.key_id NOT IN (
    SELECT k2.key_id
    FROM keys AS k2
    INNER JOIN signin AS s ON k2.key_id = s.key_id
    WHERE s.[return_date] Is Null)
GROUP BY r.room_name
ORDER BY 2 DESC