Convert SQL Query To Use Set Operators

后端 未结 1 1760
温柔的废话
温柔的废话 2021-01-26 11:17

I need to complete a SQL Query (Oracle) using a Set Operator, but I am struggling to understand how it would be implemented.

Schema:

Customer (ID, firstN         


        
1条回答
  •  一向
    一向 (楼主)
    2021-01-26 12:02

    It's not how you'd normally do this, but as an exercise, you can get the set of all customer IDs, and MINUS the set of all IDs with more than two transactions, which you can get without looking at the customer table a second time:

    SELECT C.ID
    FROM CUSTOMER C
    MINUS
    SELECT P.ID
    FROM PERFORMS P
    INNER JOIN TRANSACTION T
    ON T.CODE = P.CODE
    GROUP BY P.ID
    HAVING COUNT(T.CODE) > 1;
    

    You don't really need to join to TRANSACTION, you can just count the code values in PERFORMS directly:

    SELECT C.ID
    FROM CUSTOMER C
    MINUS
    SELECT P.ID
    FROM PERFORMS P
    GROUP BY P.ID
    HAVING COUNT(P.CODE) > 1;
    

    ... but maybe there's more to the question what you've shown, like restricting by type or date.

    0 讨论(0)
提交回复
热议问题