SQL分组问题

时间:2014-01-06 15:41:42

标签: sql oracle group-by

Neea帮助在sql中进行分组。

我喜欢

id1 id2 type
1   1   300
1   3   300
1   2   300
1   5   300
2   2   100
2   5   200
2   7   300
4   3   100
4   9   300
4   2   300

我需要只映射到一种类型的id1,
例如,id1'1'仅映射到类型300,因此只应检索它。如果有多个类型映射到id1,则不应检索它。请帮忙。
这是我尝试过的。但它只会处理类型300.
我需要检索所有id1,它们仅映射到一个特定类型。因此,如果id1'2'仅针对类型'100'进行映射,则还应该检索它。

SELECT distinct id1 from ID_TABLE where type = 300 and id1 not in 
 (SELECT id1 from type_table where type in (100, 200, 250)) 
 and id1 in ( SELECT id1 FROM ID_TABLE type=300) 
 order by id1

2 个答案:

答案 0 :(得分:2)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE tbl ( id1, id2, type ) AS
          SELECT 1,   1,   300 FROM DUAL
UNION ALL SELECT 1,   3,   300 FROM DUAL
UNION ALL SELECT 1,   2,   300 FROM DUAL
UNION ALL SELECT 1,   5,   300 FROM DUAL
UNION ALL SELECT 2,   2,   100 FROM DUAL
UNION ALL SELECT 2,   5,   200 FROM DUAL
UNION ALL SELECT 2,   7,   300 FROM DUAL
UNION ALL SELECT 4,   3,   100 FROM DUAL
UNION ALL SELECT 4,   9,   300 FROM DUAL
UNION ALL SELECT 4,   2,   300 FROM DUAL
UNION ALL SELECT 4,   4,   200 FROM DUAL
UNION ALL SELECT 5,   2,   200 FROM DUAL
UNION ALL SELECT 5,   4,   200 FROM DUAL;

查询1

SELECT   id1,
         MIN( type )
FROM     tbl
GROUP BY id1
HAVING COUNT( DISTINCT type ) = 1

<强> Results

| ID1 | MIN(TYPE) |
|-----|-----------|
|   1 |       300 |
|   5 |       200 |

答案 1 :(得分:0)

group by之后,您可能仍会有多个id1,因此having将仅限于类型为id1的情况。在这里使用MIN作为任意聚合器,因为只有一个值:

SELECT MIN(id1), type
FROM type_table
  GROUP BY type
HAVING COUNT(id1)=1;