我有一张表,后面有一行。
现在我正在执行以下查询。
select IdeaId,Count(IdeaId) as Total from testTable
where IdeaId in (100,2,3)
group by IdeaId,Status
having Status = 'Submitted'
我给了我结果。
IdeaId Total
100 1
2 1
3 1
但是我想,当我在
IN
查询中传递Idead ID时,它应该返回 只有那些所有行都有提交状态的IdeadId,如果有的话 对应于IdeaId的行具有除提交之外的状态,然后 那个想法不应该回归。
我正在使用MS SQL server 2014
答案 0 :(得分:2)
您似乎希望status
- 条款中包含where
- 条件,而不是having
条款:
select IdeaId,Count(IdeaId) as Total from testTable
where IdeaId in (100,2,3) AND Status = 'Submitted'
group by IdeaId
修改强>:
以下查询返回OP 真正想要的内容:IdeaId
仅显示的所有行状态"已提交"而没有别的:
select IdeaId, COUNT(*) Total from testTable WHERE IdeaId in (100,2,3) AND
IdeaId NOT IN (
SELECT IdeaId FROM testTable
WHERE IdeaId in (100,2,3) AND COALESCE(Status,'null') != 'Submitted'
)
在这种情况下,只有IdeaId
= 2符合此标准。
IdeaId小组
答案 1 :(得分:2)
select IdeaId, count(*) as cnt
from testTable
where IdeaId in( 2,3,100)
group by IdeaId
having count(*) = count(case when Status = 'Submitted' then 1 end)
答案 2 :(得分:0)
试试这个,
select IdeaId,Count(IdeaId) as Total from
( select distinct IdeaId from testTable
where Status = 'Submitted'
minus
select distinct IdeaId from testTable
where Status <> 'Submitted') resultTable
where IdeaId ( 100,2,3)
group by IdeaId;
答案 3 :(得分:0)
`select IdeaId,
Count(IdeaId) as Total
from testTable
where IdeaId in (100,2,3)
AND Status = 'Submitted'
and IdeaId not in (select IdeaId from testtable
where Status<> 'Submitted'
or status is null )
group by IdeaId`
我想这会给你想要的输出:)
答案 4 :(得分:-2)
你需要为你的结果使用case语句。
我考虑你使用的是mysql
select IdeaId,Count(IdeaId) as Total
from testTable
where IdeaId NOT IN(select IdeaId from testTable where Status!='Submitted')
and IdeaId IN(100,2,3)
group by IdeaId,Status