0

我有一个数据库,其中有一个查询告诉我每个特定房间总共有多少钥匙,另一个指示每个特定房间目前有多少钥匙已注销。我想创建第三个查询,指示每个房间现在有多少可用。

访问文件: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 已注销)

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 的结果。如果 Room FY218 总共有 8 个密钥,并且当前有 2 个密钥已注销。我可以结合我的查询告诉我这个房间还有 6 把钥匙吗?如果不是我怎么能得到这个结果。

在此处输入图像描述

这些是我的表格和关系:

在此处输入图像描述

4

2 回答 2

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
于 2013-01-12T09:15:42.920 回答
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
于 2013-01-12T09:03:57.493 回答