I have a table, with multiple columns, including a column named “PolicyNumber”
Here’s a sample:
PolicyNumber
NYH1111
NYD2222
SCH3333
SCS4444
LUH5555
LUS6666
ALH7777
ALW8888
VAH9999
AKH0000
...
NYH1010
NYD2318
There are 1,000+ records in this table and records contain several of each policy number types. For example, multiple policies starting with “NYH” or multiple policies starting with “VAH.”
The possible policy types are here:
NYH
NYD
SCH
SCS
LUH
LUS
ALH
ALW
VAH
AKH
How do I do a SELECT TOP 300 where it’ll INCLUDE at least one of each Policy Type? Remember, a policy type is the first 3 letters of a policy number.
Is this even possible? The purpose of this is that I have to grab 300 records from production to dump into a test environment and I need to include at least 1 of each policy. After I have at least one of each, it can be completely randomized.
You can try this:
In this solution first there is the
newid()with you can generate random order by each running.To achive the “at least one from each policy” goal, I made the
AtLeastOnecolumn. This selects the first from the randomizedCTEtable for each unique three letters at the start. If the currentPolicyequals with this first selected value, then it gets 1 else 0. So with this logic, you can select a randomized first one from each unique three letters.Note: You can put this logic directly into the
Order Bypart too if you need the Policy field only. (I made the example on this way to make the logic behind it visible)In the last step you just have to order by the
AtLeastOne Desc and then by the randomID.Here is an SQLFiddle demo.