【问题标题】:SQL: Use SET operator to get a count resultSQL:使用 SET 运算符获取计数结果
【发布时间】:2016-10-06 05:45:39
【问题描述】:

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

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

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

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

谁能帮帮我?

【问题讨论】:

    标签: sql oracle set-operations


    【解决方案1】:

    如果你必须使用集合运算符,那么你可以使用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
    

    【讨论】:

    • 我必须使用 SET 运算符。 LEFT JOIN 不是 SET 运算符。
    • @user4824195 我更新了我的答案,你也可以使用MINUS
    【解决方案2】:

    请尝试以下解决方案:

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

    希望对你有帮助。

    【讨论】:

    • 我必须使用 SET 运算符。不是关系运算符。
    【解决方案3】:
    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
    

    【讨论】:

    • 我们不需要使用 DISTINCT,因为 MINUS 只返回 DISTINCT 结果集
    • 这会返回一条错误消息 - 关系运算符无效。
    • 你能分享你的确切查询和你收到的错误吗?
    • SELECT COUNT(id_num) FROM Tree WHERE id_num MINUS (SELECT id_num FROM Bird);
    • ORA-00920:无效的关系运算符。行错误:3 列:14
    猜你喜欢
    • 1970-01-01
    • 2013-09-29
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多