0

我需要一个 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,CompletedError.

我需要列出所有只有 1 个状态的辅助 IDN,这就是输入状态。

例如我的输入是Pending:它应该只显示 57。其他人可能有Pending,但它也有完成和错误记录。

你能帮我么 ?

4

4 回答 4

5
SELECT  SECONDARY_IDN
FROM    tableName
GROUP   BY SECONDARY_IDN
HAVING  SUM(CASE WHEN Status = 'Pending' THEN 1 ELSE 0 END) = COUNT(*)
于 2013-02-03T15:43:03.400 回答
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
于 2013-02-03T15:43:26.700 回答
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具有聚合(最小,最大,计数)的解决方案可能必须扫描(和聚合)整个组以确定记录的可取性。
于 2013-02-03T15:52:48.087 回答
0
 select status
 , secondary_idn
 , count(*) records
 from theTable
 where whatever
 group by status, secondary_idn
 having count(*) = 1
于 2013-02-03T15:43:39.490 回答