减去两个查询的结果

时间:2013-01-12 07:55:54

标签: sql database ms-access database-design

我有一个带有查询的数据库,告诉我每个特定房间总共有多少个按键,另一个指示每个特定房间当前已注销的按键数量。我想创建一个第三个查询,表明现在每个房间有多少可用。

访问文件:http://jumpshare.com/b/k7pEg4

查询1(每个房间的密钥)

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;

查询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;

这是查询1和2的结果。如果FY218室有8个总密钥,2个密钥当前已注销。我可以结合我的查询告诉我这个房间还有6个钥匙。如果不是,我怎么能得到这个结果。

enter image description here

这些是我的表和关系:

enter image description here

2 个答案:

答案 0 :(得分:2)

这应该是你想要的:

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

答案 1 :(得分:0)

您可以使用子查询,如下所示:

SELECT
r.room_name,
Count(*) -
(
  SELECT Count(*)
  FROM keys AS k2
  INNER JOIN signin s2
  ON s2.key_id = k2.key_id
  WHERE r.room_id = k2.room_id
) AS AvailableKeys
FROM rooms AS r
LEFT JOIN keys AS k
ON r.room_id = k.room_id
GROUP BY r.room_name, r.room_id