Search code examples
teradatateradata-sql-assistant

Select TOP 1000 + custom user id's


I want to select top 1000 user id's based on revenue in addition to a custom list of user id's (these are not part of the top 1000)

In other words, I want the queries below in 1 query:

SELECT TOP 1000 * FROM XX
ORDER BY REVENUE DESC

SELECT * FROM XX
WHERE USER_ID IN (CUSTOM_LIST)

Solution

  • You need a Union, but as TOP is not allowed in a Set-Select you must nest it in a Derived Table:

    SELECT *
    FROM
     (
       SELECT TOP 1000 * FROM XX
       ORDER BY REVENUE DESC
     ) as dt
    
     UNION
      -- UNION ALL is more efficient, but a user from the custom list who is 
      -- also in the top 1000 would be returned twice
    
    SELECT * FROM XX
    WHERE USER_ID IN (CUSTOM_LIST)