选择不存在特定值的行

时间:2013-12-10 21:11:29

标签: sql oracle select

给出一个这样的表:

SESS_CODE   YEAR    Count   ID
----        ----    ----    ----
D           2014    1       51
W           2014    1       51
            2014    2       51
O           2014    1       52
W           2014    1       52
            2014    2       52
D           2014    2       53
O           2014    1       54
W           2014    1       55

我正在尝试写一个返回SESS_CODE ='D'的行的查询,除非该ID位于另一行,其中SESS_CODE是除“D”之外的其他行。所以结果应该是:

SESS_CODE   YEAR    Count   ID
----        ----    ----    ----
D           2014    2       53

3 个答案:

答案 0 :(得分:0)

试试这个:

select *
from Table T1
where SESS_CODE = 'D'
    and not exists (select * 
                    from Table T2 
                    where T1.Id = T2.Id 
                        and T2.SESS_CODE != 'D')

答案 1 :(得分:0)

SELECT * FROM table WHERE SESS_CODE = 'D' 
AND ID NOT IN(SELECT ID FROM table WHERE SESS_CODE != 'D')

SQL Fiddle

答案 2 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE Data ( SESS_CODE, YEAR, "Count", ID ) AS
          SELECT 'D',           2014,    1,       51 FROM DUAL
UNION ALL SELECT 'W',           2014,    1,       51 FROM DUAL
UNION ALL SELECT NULL,          2014,    2,       51 FROM DUAL
UNION ALL SELECT 'O',           2014,    1,       52 FROM DUAL
UNION ALL SELECT 'W',           2014,    1,       52 FROM DUAL
UNION ALL SELECT NULL,          2014,    2,       52 FROM DUAL
UNION ALL SELECT 'D',           2014,    2,       53 FROM DUAL
UNION ALL SELECT 'O',           2014,    1,       54 FROM DUAL
UNION ALL SELECT 'W',           2014,    1,       55 FROM DUAL;

查询1

一个分析函数和一个过滤器(无连接):

WITH Max_Sess_Codes AS (
  SELECT SESS_CODE,
         YEAR,
         "Count",
         ID,
         MAX( SESS_CODE ) KEEP ( DENSE_RANK FIRST ORDER BY DECODE( SESS_CODE, 'D', 1, 0 ) ) OVER ( PARTITION BY ID ) AS max_sess_code
  FROM   Data d
)
SELECT SESS_CODE,
       YEAR,
       "Count",
       ID
FROM   Max_Sess_Codes
WHERE  max_sess_code = 'D'

<强> Results

| SESS_CODE | YEAR | COUNT | ID |
|-----------|------|-------|----|
|         D | 2014 |     2 | 53 |

查询2

如果您对UNIQUESESS_CODE有一个复合ID约束(即,对于每个ID,只有一行SESS_CODE为'D' )然后你可以使用:

SELECT MAX( SESS_CODE ) AS SESS_CODE,
       MAX( year ) AS year,
       MAX( "Count" ) AS "Count",
       ID
FROM   Data
GROUP BY ID
HAVING COUNT( CASE SESS_CODE WHEN 'D' THEN NULL ELSE 1 END ) = 0

<强> Results

| SESS_CODE | YEAR | COUNT | ID |
|-----------|------|-------|----|
|         D | 2014 |     2 | 53 |