I have read this question:
What is the best way to get a random ordering?
and can do a select top 4 from tabel order by NEWID()
but I need it per category.
So I need 1 row from category A, 1 row from category B, 1 row from category C and 1 row from parentcategory D.
So I tried to union them and I tried to add a wrapping select query which told me that I could not order the subquery... So I am stuck.
Here is the SQL I have so far:
SELECT top 4 Artikel.ArtikelID -- etc.
FROM Artikel
INNER JOIN Categorie ON Artikel.CategorieID = Categorie.CategorieID
INNER JOIN CategorieTaal ON Categorie.CategorieID = CategorieTaal.CategorieID
INNER JOIN CategorieGroep on Categorie.CategorieGroepID = CategorieGroep.CategorieGroepID
INNER JOIN CategorieGroepTaal on CategorieGroep.CategorieGroepID = CategorieGroepTaal.CategorieGroepID
INNER JOIN Taal ON CategorieTaal.TaalCode = Taal.TaalCode AND ArtikelTaal.TaalCode = Taal.TaalCode and CategorieGroepTaal.TaalCode = taal.TaalCode
INNER JOIN Levertijd ON Artikel.LevertijdID = Levertijd.LevertijdID
WHERE (ParentCategorieID = 292 or artikel.CategorieID = 246 or artikel.CategorieID = 247 or artikel.CategorieID = 288)
and taal.taalcode = 'EN'
order by NEWID()
current result could contain 4 rows all of the same category. That is not what I want. It's a bit different than the possible duplicate because it is not grouped on 1 column, but two different once.
ROW_NUMBER() OVER (PARTITION
before but I do not know what the best approach is, since the fourth row should be from a certain parentcategory instead of normal category. I have never looked intoApply
so will do that asap.