我有一个这种结构的表格:
ID TaskID ResourceID IsActive
--- ----- ---------- --------
1 51 101 1
2 52 101 1
3 53 101 1
4 51 102 0
5 52 102 0
6 53 102 0
7 51 103 1
8 52 103 0
9 53 103 1
我想获取所有记录中IsActive
列为0的资源。在这个例子中,我想得到ResourceID-102作为结果,因为它的IsActive
列都是0。
我尝试过:
select ResourceID
from TableName
where ResourceID <> (SELECT ResourceID
from TableName
group by ResourceID, IsActive
having IsActive = 1)
在子查询中,我正在尝试获取所有具有IsActive = 1的资源。但是当没有任何记录具有IsActive = 1时,它不返回任何结果。因此我的主查询也失败了。关于如何实现我的结果的任何建议?
编辑:
解决方案:
select distinct ResourceID
from TableName t1
where not exists (select 1 from TableName t2
where t1.ResourceID = t2.ResourceID
and t2.IsActive = 1)
此外,我认为我的问题很简单,而不是“可能重复”。未来的读者可能会发现这个问题比建议的副本更容易联系起来。用户更有可能通过“SQL Server groupby two columns”而不是“SQL:选择没有任何具有特定值的行的ID”来搜索此问题。
答案 0 :(得分:2)
SELECT ResourceID
FROM
TableName T
WHERE
NOT EXISTS
(
SELECT *
FROM TableName
WHERE
ResourceID = T.ResourceID AND
IsActive = 1
)
或者...
SELECT ResourceID
FROM
TableName
GROUP BY
ResourceID
HAVING
MAX(IsActive) = 0
答案 1 :(得分:1)
只要具有相同ResourceID的其他行没有IsActive = 1:
,就返回一行select ResourceID
from TableName t1
where not exists (select 1 from TableName t2
where t1.ResourceID = t2.ResourceID
and t2.IsActive = 1)
也许您希望select distinct ResourceID
删除重复项。
答案 2 :(得分:0)
Discovered UUID: 0000fff1-0000-1000-8000-00805f9b34fb
Discovered UUID: 0000fff2-0000-1000-8000-00805f9b34fb
Discovered UUID: 0000fff3-0000-1000-8000-00805f9b34fb
Discovered UUID: 0000fff4-0000-1000-8000-00805f9b34fb
Discovered UUID: 0000fff5-0000-1000-8000-00805f9b34fb
答案 3 :(得分:0)
select ResourceID
from TableName
group by ResourceID
having max(IsActive) = 0