我需要SQL Server和Oracle兼容查询才能获得以下结果
表:
PRIMARY IDN SECONDARY_IDN STATUS
1 47 Pending
2 47 Completed
3 47 Error
4 57 Pending
5 59 Completed
6 60 Pending
7 60 Completed
我的输入可以是Pending
,Completed
或Error
。
我需要列出只有1个状态的所有辅助IDN,这是输入状态。
例如我的输入是Pending
:它应该只显示57。其他人可能有Pending
,但也有完成和错误记录。
你能帮帮我吗?
答案 0 :(得分:5)
SELECT SECONDARY_IDN
FROM tableName
GROUP BY SECONDARY_IDN
HAVING SUM(CASE WHEN Status = 'Pending' THEN 1 ELSE 0 END) = COUNT(*)
答案 1 :(得分:3)
您需要只有一个状态的群组。为此,您希望使用聚合:
select secondary_idn
from t
group by secondary_idn
having max(status) = min(status) and -- all the statuses are the same
max(status) = 'Pending' -- and the status is Pending
答案 2 :(得分:1)
SELECT *
FROM tableName tn
WHERE tn.Status = 'Pending'
AND NOT EXISTS ( SELECT *
FROM tableName nx
WHERE nx.SECONDARY_IDN = tn.SECONDARY_IDN
AND nx.Status <> 'Pending'
);
group by
,因此所有列都可用(可怕的select *
就是为了说明这一事实)exists
需要检测只有一个不需要的记录才能产生true
,具有聚合(min,max,count)的解决方案可能必须扫描(并聚合)< em>整个小组以确定记录的可取性。答案 3 :(得分:0)
select status
, secondary_idn
, count(*) records
from theTable
where whatever
group by status, secondary_idn
having count(*) = 1