I need to (safely) handle the case where there is < 5 “reviews” for a product (even none). In addition, being able to define the ordering of the “reviews” is important. I would prefer a solution that would work with both SQL Server and PostgreSQL (with minor modification). I would be willing to use PIVOT as a last resort, but from what I have read it won’t do what I want it to do.
Table1
id, product
1, ‘Product 1’
2, ‘Product 2’
Table2
id, review
1, ‘review #1a’
1, ‘review #1b’
1, ‘review #1c’
1, ‘review #1d’
1, ‘review #1e’
1, ‘review #1f’
2, ‘review #2a’
2, ‘review #2b’
2, ‘review #2c’
2, ‘review #2d’
2, ‘review #2e’
2, ‘review #2f’
Result
1, ‘Product 1’, ‘review #1a’, ‘review #1b’, ‘review #1c’, ‘review #1d’, ‘review #1e’
2, ‘Product 2’, ‘review #2a’, ‘review #2b’, ‘review #2c’, ‘review #2d’, ‘review #2e’
Try this (tweaked to refer to the appropriate things):
The idea is… use row_number() to get up to 5 reviews out per product. Then pivot the results, and then do a left join to get product details (including those that don’t have any reviews).