SQL查询使用查询同一个表的子查询来过滤行

时间:2016-05-11 03:15:22

标签: mysql sql-server nested-queries

我正在尝试构建一个基于其他行过滤行的查询,如下例所示

TableA

Id    status        type       date
300   approved      ACTIVE    11/12/2015 10:00:00
300   approved      ACTIVE    11/12/2015 10:10:00
300   approved      INACTIVE  11/12/2015 11:00:00
200   approved      ACTIVE    11/12/2015 11:10:00
200   approved      INACTIVE  11/12/2015 11:10:00
100   approved      ACTIVE    11/12/2015 11:10:00

从上表中我试图返回具有相同数量的ACTIVE和INACTIVE类型的ID,例如Id 300有两行类型为ACTIVE,一行类型为INACTIVE,因此Id 300应从我的结果中排除,其中200为200有1个活动,1个非活动,它应该包含在结果中

在上表状态中,类型也可以有其他值,但我只关心上面列出的那些忽略其他值

因此,对于TableA,查询的最终结果将是

Id
200

我尝试运行以下查询,但这并没有给我预期的结果

SELECT Id
FROM TableA oa
WHERE oa.type in('ACTIVE','INACTIVE') 
and oa.status='APPROVED'
 and not EXISTS(SELECT
            x.id
            ,COUNT(*)
        FROM (SELECT DISTINCT
                id
                ,c.type
            FROM TableA c
            WHERE 
            AND c.type IN ('ACTIVE','INACTIVE')
            AND c.status = 'APPROVED'
            AND c.Id= ta.Id
            )x
        GROUP BY x.Id
        HAVING COUNT(*) = 1)

可以更正上述查询以获得所需的结果吗?

1 个答案:

答案 0 :(得分:4)

您只需使用SUMHAVING

SELECT Id
FROM TableA 
WHERE 
    status = 'approved'
    AND type In ('ACTIVE', 'INACTIVE')
GROUP BY Id
HAVING
    SUM(CASE WHEN type = 'ACTIVE' THEN 1 ELSE 0 END) = 
    SUM(CASE WHEN type = 'INACTIVE' THEN 1 ELSE 0 END)