Reputation: 113
This is my table1
ID || Basket || Balls
--------------------------
1 || Ram || 1
1 || Rom || 3
2 || Ram || 2
3 || Rom || 5
Query - Select all the IDs that have both at least 1 ball in both Ram and Rom.
----All the IDs that have at least 1 ball in Ram
SELECT distinct ID
INTO #RAM
FROM Table1
where balls > =1 and basket = 'Ram'
----All the IDs that have at least 1 ball in Rom
SELECT distinct ID
INTO #ROM
FROM Table1
where balls > =1 and basket = 'Rom'
---All the IDs that have both
Select distinct ID
INTO #FinalTable
from #RAM a join #ROM b on a.id = b.id
This is what I have written so far it works but I feel there is definitely a more efficient way to do this.
Please let me know. Thank you.
Upvotes: 0
Views: 55
Reputation: 1642
We can group by based on ID,Basket and select records having count greater than 1
select distinct a.id from
(
select id,basket,count(balls) as cn
from table1
group by id,basket
having cn>1
) a ;
Upvotes: 0
Reputation: 1269503
I would use a single aggregation:
select id
from table1 t1
group by id
having sum(case when basket = 'Ram' then balls end) > 0 and
sum(case when basket = 'Rom' then balls end) > 0;
Assuming the value of balls
is never negative or zero, then you only need to check that that the rows exist. That is a little simpler in MySQL:
select id
from table1 t1
group by id
having sum(basket = 'Ram') > 0 and
sum(basket = 'Rom') > 0;
Upvotes: 2
Reputation: 49373
You need Only t use this query and combine your Queries
SELECT
a.ID
FROM (SELECT ID FROM Table1 Where Balls >= 1 And Basket = 'RAM') a
INNER JOIN (SELECT ID FROM Table1 Where Balls >= 1 And Basket = 'ROM') b
ON a.ID = b.ID
It only return the OD that are have nmore than 1 ball and are in RoM and RAM
Upvotes: 0
Reputation: 13006
You can use subqueries
to achieve this.
- join RAM
- join ROM
- select count() >= 1
select t1.ID
from Table1 t1
join
(select ID, count(1) ct from Table1 where Basket = 'Ram'
group by ID) as ram on ram.ID = t1.ID
join
(select ID, count(1) ct from Table1 where Basket = 'Rom'
group by ID) as rom as rom.ID = t1.ID
where ram.ct >= 1 and rom.ct >= 1
Upvotes: 0