与HAVING条件分组

时间:2016-11-03 13:14:40

标签: sql sql-server

我有一个包含以下字段的表格。

enter image description here

我想在Account_Id组中 Invalid_vod中输出状态

Account_Id  Address_Id  Status
AC001       ADD12345    Invalid_vod
AC003       ADD12348    Invalid_vod
AC003       ADD12349    Invalid_vod

我这样做但却无法得到我想要的结果。

select [Account_Id],[Address_Id],[Status]
  from [DBFile]
  group by [Account_Id],[Address_Id],[Status]
  having [Status] = 'Invalid_vod'

3 个答案:

答案 0 :(得分:2)

您可以使用COUNT的窗口版本:

;with cte as (
   select [Account_Id], [Address_Id], [Status],
          count(case when [Status] <> 'Invalid_vod' then 1 end)
          over (partition by [Account_Id]) AS cnt
   from [DBFile]
)
select [Account_Id], [Address_Id], [Status]
from cte
where cnt = 0

答案 1 :(得分:2)

您可以像这样查询

public int ID { get; }

答案 2 :(得分:0)

WITH CandidateAccounts AS (
     SELECT Account_Id
       FROM DBFile
      WHERE Status = 'Invalid_vod'
     EXCEPT 
     SELECT Account_Id
       FROM DBFile
      WHERE Status <> 'Invalid_vod' )
SELECT Account_Id, Address_Id, Status
  FROM DBFile
 WHERE Status = 'Invalid_vod'  -- not enough data to be
                               -- sure about this
       AND Account_Id IN ( SELECT Account_Id
                             FROM CandidateAccounts );