Link to home
Start Free TrialLog in
Avatar of gram77
gram77Flag for India

asked on

query to produce 10 rows, half of col= A and other half of col=B

I have a table my_table
I want a query which selects 5 rows where col='A' and 5 rows where col='B'
so i should have a total of 10 rows.

but the following query does not work as intended.

select col
from my_table
where col= 'A'
and rownum<=5
union
select col
from my_table
where col= 'B'
and rownum<=5

Avatar of data_n_poker
data_n_poker

Try using union all instead of just union
Avatar of gram77

ASKER

union all and union work same.
also i only see col=A rows, col=B rows do not append
Try this:

Select *
From 
(select col
from my_table
where col= 'A'
and rownum<=5) colA,
(select col
from my_table
where col= 'B'
and rownum<=5) colB
ORDER BY Col

Open in new window

Avatar of Sean Stuber
you can also try this



SELECT col
  FROM (SELECT col, ROW_NUMBER() OVER (PARTITION BY col ORDER BY 1) rn
          FROM my_table
         WHERE col IN ('A', 'B'))
 WHERE rn <= 5
Avatar of gram77

ASKER

above query returns no rows.
are you sure you're explaining your setup correctly?

the union all suggestion and my row_number suggestion both work when I tested them.

if they don't work for you, please post structure and sample data that illustrates the problem
ASKER CERTIFIED SOLUTION
Avatar of data_n_poker
data_n_poker

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
gram77,

please explain your choice.
the accepted answer does not produce the requested results of 10 rows.

It will produce a cartesian product based on the results of two subqueries.
Assuming each subquery returns 5 rows, the result will be 25 rows for the entire query
Also, it won't return a single column it will return 2 columns
and lastly,  the order by clause in that post is syntactically incorrect because "col" is ambiguous
I have the same question, as i posted that before i tried it, and it is very much incorrect(syntactically and based on what is asked for in the question).  Thought the union all and sdstuber's query provided the exact results that were requested.
Avatar of gram77

ASKER

that is an error on my part.
by mistake i accepted the wrong solution,
the correct one is
ID: 35208415
sure,  UNION ALL was the very first post and from the same author
http:#a35208415 repeats it but with an example.