I got a parent table 'ProductCategory' and a child table 'Product'. I have this query that returns 3 random products:
SELECT TOP (3) ProductId
FROM Product
ORDER BY NEWID();
I want to enhance that query to achieve that all the products are from different product categories. So the query to get unique categories would be:
SELECT TOP (3) ProductCategoryId
FROM ProductCategory
ORDER BY NEWID();
I am not able to figure out how to combine those 2 queries to achieve my goal. The obvious query
SELECT TOP (3) p.ProductId
FROM Product p
where p.productcategory_ProductCategoryId in
(
SELECT TOP (3) ProductCategoryId pc
FROM ProductCategory pc
ORDER BY NEWID()
)
ORDER BY NEWID();
does not work. It seems like the inner select statement is ignored. I also tried with the EXISTS statement or joining the tables. All with the same result.
Does someone have an idea? Thanks a lot in advance!