Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select first x records per group

Am using the query below to search for products that contain a term in their title. The query returns the desired results (often too many results).

Now I only want it to be able choose a maximum of 3 (random) products per company. Some companies return many records/products, but I only need to take 3 and move on to the next company

SELECT p.title As entryname, cname 
FROM company c, product p
WHERE p.title LIKE '%steel%' AND p.cid = c.cid 
GROUP By cname, ca.title

I tried to understand the partition by and rank thing but I did not get too far. I am using ms sql

like image 526
TDaddy Hobz Avatar asked Nov 25 '25 06:11

TDaddy Hobz


1 Answers

You can use ROW_NUMBER() to do 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 want random (instead of the 3 with the lowest ID) you can change the row_number line to

ROW_NUMBER() OVER (PARTITION BY c.id order by newid()) rn

like image 97
Conrad Frix Avatar answered Nov 27 '25 22:11

Conrad Frix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!