dimanche 25 octobre 2020

How to select random rows in tsql with priorities for some rows

My question is an extension of the question asked here: How to request a random row in SQL?

What is the extension? Let's say is given a table of users, with this structure:

id (int) | name | email | phone number (char)

If I want to select few random users I have this query:

SELECT TOP @X column FROM table ORDER BY NEWID()

The extension I need is to give priority to users that have phone number (NOT NULL). The users should be randomly selected, but the one with phone number (if any) should come first, and the total number of returned rows should still be @X.

Thank you.




Aucun commentaire:

Enregistrer un commentaire