查询具有两个 ID 字段的 Table
Querying a Table with two ID Fields
我有一个名为 Actions
的 table,有 2 个标识符:Ref
和 Status
状态可以是以下任何一种:new
、done
Ref | Status | Date
----------------------------------
1 | new | 10/31/2018
1 | done | 10/31/2018
2 | new | 10/31/2018
我只想查询 new
而不是 done
的操作。在此示例中,查询将仅 return table.
的第 3 行
到目前为止,这是我尝试过的方法,但我只获得了已置于状态的操作 done
:
SELECT [2].[project title], [2].ref, [2].[Date] As [Creation Date]
FROM (SELECT * From T_ACTIONS Where status = "New") AS [1],
(SELECT * From T_ACTIONS Where status = "Done") AS [2]
WHERE [1].[Project Title] = [Insert a valid : Project Title]
AND [1].[REF] = [2].[Ref]
我使用的是 Access 2016。
使用NOT EXISTS
:
SELECT a.*
FROM Actions a
WHERE Status = 'new' AND
NOT EXISTS (SELECT 1 FROM Actions a1 WHERE a1.REF = a.REF AND a1.Status = 'Done');
您可以 LEFT JOIN
您的操作 table 到嵌套 SELECT
查询检索状态为 Done
的所有引用,并测试在嵌套查询,例如:
SELECT a.*
FROM
Actions a LEFT JOIN (SELECT b.Ref FROM Actions b WHERE b.Status = 'Done') t
ON a.Ref = t.Ref
WHERE
a.Status = 'New' AND t.Ref IS NULL
另一种方法使用聚合:
select ref
from actions
where status in ('new', 'done')
group by ref
having min(status) = max(status) and min(status) = 'new';
我有一个名为 Actions
的 table,有 2 个标识符:Ref
和 Status
状态可以是以下任何一种:new
、done
Ref | Status | Date
----------------------------------
1 | new | 10/31/2018
1 | done | 10/31/2018
2 | new | 10/31/2018
我只想查询 new
而不是 done
的操作。在此示例中,查询将仅 return table.
到目前为止,这是我尝试过的方法,但我只获得了已置于状态的操作 done
:
SELECT [2].[project title], [2].ref, [2].[Date] As [Creation Date]
FROM (SELECT * From T_ACTIONS Where status = "New") AS [1],
(SELECT * From T_ACTIONS Where status = "Done") AS [2]
WHERE [1].[Project Title] = [Insert a valid : Project Title]
AND [1].[REF] = [2].[Ref]
我使用的是 Access 2016。
使用NOT EXISTS
:
SELECT a.*
FROM Actions a
WHERE Status = 'new' AND
NOT EXISTS (SELECT 1 FROM Actions a1 WHERE a1.REF = a.REF AND a1.Status = 'Done');
您可以 LEFT JOIN
您的操作 table 到嵌套 SELECT
查询检索状态为 Done
的所有引用,并测试在嵌套查询,例如:
SELECT a.*
FROM
Actions a LEFT JOIN (SELECT b.Ref FROM Actions b WHERE b.Status = 'Done') t
ON a.Ref = t.Ref
WHERE
a.Status = 'New' AND t.Ref IS NULL
另一种方法使用聚合:
select ref
from actions
where status in ('new', 'done')
group by ref
having min(status) = max(status) and min(status) = 'new';