我想找到不同的FKID,其中IsProcessed对于相同的FKID是真的。 e.g。
CID FKID DataField IsProcessed
1 1 Test 1
2 1 Test 1
3 2 Test 0
4 2 Test 1
5 3 Test 0
6 3 Test 0
7 4 Test 1
8 5 Test 0
9 6 Test 1
10 6 Test 1
11 6 Test 1
我想获得以下FKID返回1,4,6 因为这些是所有实例的isprocessed为真的FKID。
任何帮助将不胜感激!谢谢!
答案 0 :(得分:1)
您可以使用SUM() OVER
和COUNT() OVER
;WITH CTE AS(
SELECT
*,
IsProcessedCount = SUM(CASE WHEN IsProcessed = 1 THEN 1 ELSE 0 END) OVER(PARTITION BY FKID),
cc = COUNT(*) OVER(PARTITION BY FKID)
FROM TEST
)
SELECT
DISTINCT FKID
FROM CTE
WHERE IsProcessedCount = cc
使用GROUP BY
和HAVING
:
SELECT FKID
FROM Test
GROUP BY FKID
HAVING COUNT(FKID) = COUNT(CASE WHEN IsProcessed = 1 THEN 1 ELSE NULL END)
另一种方式:
SELECT FKID
FROM Test
GROUP BY FKID
HAVING COUNT(FKID) = SUM(CAST(IsProcessed AS INT))
只需将TEST
替换为您的表格。
答案 1 :(得分:1)
SELECT FKID
FROM TableName
GROUP BY FKID
HAVING (MIN(IsProcessed) = 1)
或者
SELECT FKID
FROM TableName
GROUP BY FKID
HAVING (MIN(CAST(IsProcessed AS INT)) = 1)
如果IsProcessed不是数字类型:
答案 2 :(得分:1)
另一种方法,使用相关的not exists
谓词:
select fkid from TableName t
where IsProcessed = 1
and not exists
(select 1 from TableName where IsProcessed = 0 and FKID = t.FKID)
group by fkid
或使用not in
:
select fkid from TableName t
where IsProcessed = 1
and fkid not in
(select fkid from TableName where IsProcessed = 0 and FKID = t.FKID)
group by fkid