Gintarė Sunn
Gintarė Sunn

Reputation: 1

Set quantity of different values

I'm kinda fresh in SQL and I really need help :) I have a code:

select *
from table1
where action_code_is in ('pink', 'yellow', 'blue', 'green') 
AND group = 'colors'

What I want to filter is only values in action_code_is (I have thousands) which I wrote. The main thing is that I want to have only 4 pink values, 5 yellow, 6 blue and 3 green. Could someone help me? I'm not sure how to see only a set quantity of actions not all values from table.

Upvotes: 0

Views: 35

Answers (1)

Barmar
Barmar

Reputation: 781004

Use separate queries for each color, so you can specify different LIMIT values. Then combine them with UNION.

(SELECT *
FROM table1
WHERE action_code = 'pink' AND `group` = 'colors'
LIMIT 4)
UNION ALL
(SELECT *
FROM table1
WHERE action_code = 'yellow' AND `group` = 'colors'
LIMIT 5)
UNION ALL
(SELECT *
FROM table1
WHERE action_code = 'blue' AND `group` = 'colors'
LIMIT 6)
UNION ALL
(SELECT *
FROM table1
WHERE action_code = 'green' AND `group` = 'colors'
LIMIT 3)

Note that LIMIT without ORDER BY will result in unpredictable selections of the rows.

Upvotes: 1

Related Questions