This is a question for a SQL specialist!
I’m using SQL SERVER 2008 R2 Express.
I have a table named [myTable] consist of 2 types of records.
The 1st type of records is a master record and the second type is a [Relative] record.
Each master record might have several related record.
I would like to SLELECT TOP 10 * FROM [myTable] master records, and the union sub records like SELECT TOP 4 of [Relative] records for each.
Each record has a [PKID] NO NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED column.
I think I need something like that:
SELECT TOP 10 * FROM [myTable] WHERE [Relative]=0
UNION
For each (SELECT TOP 10 [PKID] as Master, * FROM [myTable] WHERE [Relative]=0 )
{SELECT TOP 4 * FROM [myTable] WHERE [Relative] = Master}
How should I correct the query in order to achieve my goal?
I have a secondary question which I doubt there is a simple solution for it:
Relative records comes in two flavors as described by the column [IsImportant].
Is there a way to make sure only 1 important relative record will be selected for each master record?
Is there a way to skip a master record if there are less then 4 relative records for it while only 1 of them is important?
EDIT
Is this a correct paraphrase of your requirements?
[myTable] has 3 relevant fields…
IsImportant : 0/1 flag
Questions:
– If a master has 3 relative records, and none of them are isImportant, still skip?
– If a master has 4 relative records, and more than 1 is isImportant, still skip?
Best guess answer…