查询根据另一行的过滤器排除行

时间:2011-06-10 16:52:05

标签: oracle rows

我正在使用Oracle 10g。

问题:如果该ID的所有代码都以6结尾,那么如何才能编写查询以仅返回ID?

我不希望ID = 1,因为并非所有代码都以6结尾。

TABLE_A

ID  Code
===============
1   100  
1   106
2   206
3   316
3   326
4   444

Desired Result:
ID
==
2
3

2 个答案:

答案 0 :(得分:2)

您只需要每个ID,其中该id的行数与第三个数字为6的行数相同。

SELECT ID
FROM TABLE_A
GROUP BY ID
HAVING COUNT(*) = COUNT(CASE WHEN SUBSTR(code,3,1) = '6' THEN 1 END)

答案 1 :(得分:1)

试试这个:

SELECT DISTINCT b.id
  FROM (
        SELECT id, 
                COUNT(1) cnt
          FROM table_a  
         GROUP BY id 
        ) a,
        (
        SELECT id, 
                COUNT(1) cnt
          FROM table_a  
         WHERE CODE LIKE '%6'
         GROUP BY id
        )b
WHERE a.id = b.id
  AND a.cnt = b.cnt

替代使用ANALYTIC函数:

SELECT DISTINCT id   
  FROM 
    (
    SELECT  id, 
            COUNT(1)  OVER(PARTITION BY id) cnt,
            SUM(CASE WHEN code LIKE '%6' THEN 1 ELSE 0 END) OVER(PARTITION BY id) sm
        FROM  table_a 
  )
WHERE cnt = sm