You can use ROW_NUMBER () for this
with cte as (
SELECT
p.title as entryname, cname,
ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY p.id) rn
FROM company c
INNER JOIN product p
ON p.cid = c.cid
WHERE p.title LIKE '%steel%'
GROUP By cname, ca.title
)
SELECT
p.title as entryname, cname,
FROM CTE where rn <= 3
If you really need a random one (instead of the 3 with the lowest ID), you can change the row_number string to
ROW_NUMBER() OVER (PARTITION BY c.id order by newid()) rn
source
share