我有一个表定义如下:
CREATE TABLE A_TEST (
"ID" NUMBER NOT NULL ENABLE,
"TYPE" VARCHAR2(20 BYTE),
)
如果我想获得不同类型的ID,我会写这个查询:
SELECT distinct a1.ID FROM A_TEST a1
JOIN A_TEST a2 on a2.ID = a1.ID and a2.type != a1.type
但是我怎样才能找到我定义了单一类型的ID? (Id只有一行,id只有很多行,只有一行有定义的类型)
答案 0 :(得分:4)
以下查询将返回表中只有一个TYPE的所有ID。
SELECT ID FROM A_TEST
WHERE TYPE IS NOT NULL -- since TYPE column can be NULL for a given ID.
GROUP BY ID
HAVING COUNT(*) = 1
E.g。
CREATE TABLE A_TEST ( ID INT, TYPE INT)
INSERT INTO A_TEST VALUES(1, NULL)
INSERT INTO A_TEST VALUES(2, 0)
INSERT INTO A_TEST VALUES(3, 0)
INSERT INTO A_TEST VALUES(3, 1)
INSERT INTO A_TEST VALUES(4, 1)
INSERT INTO A_TEST VALUES(4, 1)
INSERT INTO A_TEST VALUES(5, 0)
INSERT INTO A_TEST VALUES(5, NULL)
SELECT
ID
FROM
A_TEST
WHERE
TYPE IS NOT NULL -- since TYPE column can be NULL for a given ID.
GROUP BY ID
HAVING COUNT(ID) = 1
结果
ID
-----------
2
4
(2 row(s) affected)
答案 1 :(得分:3)
此示例考虑了NULL值类型:
SELECT ID
FROM A_TEST
WHERE TYPE IS NOT NULL
GROUP BY ID
HAVING COUNT(DISTINCT TYPE)=1
例如,请参阅SQL Fiddle
答案 2 :(得分:3)
在澄清之后,您的要求似乎是:
SELECT ID
FROM A_TEST
GROUP BY ID
HAVING COUNT(DISTINCT TYPE) = 1
OR COUNT(*) = 1 ;