I have a table with entries from which two entries are supposed to be selected. The probability of some entries to be selected should be higher than the probability of others.
Currently I solve this with UNION ALL accordingly I select once all entries and then again the entries which should have a higher probability. From this merged table I select then after the call of ORDER BY NEWID() for mixing with TOP 2 two entries.
SELECT TOP 2 EMail
FROM (
SELECT EMail
FROM dbo.Benutzer
UNION ALL
SELECT EMail
FROM dbo.Benutzer
WHERE param1 = 1
UNION ALL
SELECT EMail
FROM dbo.Benutzer
WHERE param2 = 1
) AS EMail
ORDER BY NEWID();
Example table:
EMail param1 param2
______________|_________|___________
Test@test.com |0 | 0 -> probability is 1 (normal)
Test1@test.com|1 | 0 -> probability is 2 (higher than 1)
Test2@test.com|1 | 0 -> probability is 2 (higher than 1)
Test3@test.com|1 | 1 -> probability is 3 (higher than 1 and 2)
Test4@test.com|1 | 0 -> probability is 2 (higher than 1)
Test5@test.com|1 | 0 -> probability is 2 (higher than 1)
so if I make a select from this table and shuffle it before that, that with each new select different data comes out, the probability should be based on this table. So how likely it is that this entry comes up.
Always two different users should come out. e.g. Test3 and Test4. However, also Test unf Test3 so it should be only a probability.
However, this query is not performat. How can this problem be solved in a performant way?