SQL:使用SET运算符获取计数结果

时间:2016-10-06 05:45:40

标签: sql oracle set-operations

我正在尝试使用SQL Developer中的SET运算符来获取计数结果。

我必须找到“table_name1”中有多少“attribute1”但不在“table_name2”中

基本上我想要从以下查询获得的结果,但是使用SET运算符。

{{1}}

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

请尝试以下解决方案:

SELECT count(distinct <attribute1>)
FROM <table_name1>
WHERE <attribute1> NOT IN (SELECT <attribute1>
                           FROM <table_name2>);

我希望这会对你有所帮助。

答案 1 :(得分:0)

如果必须使用集合运算符,则可以使用MINUS

来解决此问题
SELECT COUNT(*)                      -- use COUNT(DISTINCT attribute1) to avoid
FROM                                 -- duplicates
(
    SELECT attribute1
    FROM table_name1
    MINUS
    SELECT attribute1
    FROM table_name2
) t

但是,我可能会在这里使用LEFT JOIN,因为它在概念上很简单:

SELECT COUNT(DISTINCT t1.attribute1) -- replace with COUNT(*) to count duplicates
FROM table_name1 t1
LEFT JOIN table_name2 t2
    ON t1.attribute1 = t2.attribute1
WHERE t2.attribute1 IS NULL          -- indicates that attribute does NOT appear in
                                     -- the second table

答案 2 :(得分:0)

SELECT COUNT(<attribute1>)
FROM <table_name1>
WHERE <attribute1> MINUS (SELECT <attribute1>
                           FROM <table_name2>);

https://docs.oracle.com/cd/B19306_01/server.102/b14200/operators005.htm

更新回答

SELECT COUNT(X.id_num)
(SELECT id_num
FROM Tree 
WHERE id_num)
MINUS 
(SELECT id_num 
FROM Bird) AS X