Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I do a select a limited number of rows with the same attribute?

Tags:

sql

postgresql

I have a table of URLs and one attribute is the domain.

Supposing I have 100 URLs from Google, 100 from Facebook, 100 from Ebay and the same for others domains, but I want to retrieve the first 30 URLs from Google, 30 from Facebook, 30 from Ebay and 30 from the others limiting to a max of 500 URLs.

How I do this?

like image 559
Renato Dinhani Avatar asked Oct 11 '22 14:10

Renato Dinhani


2 Answers

The following SQL resolves my case, but the urls are out of order because the row_number don't follow the orders. I think this SQL need some improvement.

SELECT url,row_number FROM(
     SELECT url,row_number() OVER (PARTITION BY domain) FROM website
     WHERE domain IN
    (SELECT DISTINCT domain FROM link)  
) AS links 
WHERE row_number <= 10
LIMIT 25
like image 54
Renato Dinhani Avatar answered Oct 20 '22 06:10

Renato Dinhani


How about something like this:

SELECT url FROM link WHERE domain='Google' LIMIT 30
UNION
SELECT url FROM link WHERE domain='Facebook' LIMIT 30
UNION
SELECT ...

etc.

like image 40
duduamar Avatar answered Oct 20 '22 06:10

duduamar