Reputation: 5291
I have a table
id = 1
name = 'one'
group = 1
id = 2
name = 'two'
group = 1
id = 3
name = 'three'
group = 2
and i have to get in one sql query all names which are singles, in this case id = 3 and another sql all names which are multiples, in this case id=1 and id=2, since they have the same group. I suppose it should be a select in select but not sure.
Thanks in advance.
Upvotes: 0
Views: 116
Reputation: 247700
It sounds like you want to use something similar to this:
select id
from yourtable
group by `group`
having count(`group`) = 1
See SQL Fiddle with Demo.
Then if you want to return all details, then you can expand the query to:
select *
from yourtable t1
where id in (select id
from yourtable t2
group by `group`
having count(`group`) = 1)
See SQL Fiddle with Demo.
If you want to return all rows that have the same group, then you can use:
select *
from yourtable t1
where `group` in (select `group`
from yourtable t2
group by `group`
having count(`group`) > 1)
Then if you want to return everything and a flag that identifies if it is a single or multiple, then you can use something similar to this. You will notice that I included a flag to show what groups
have one row and then what groups have more than one row:
select *, 'single' Total
from yourtable t1
where `group` in (select `group`
from yourtable t2
group by `group`
having count(`group`) = 1)
union all
select *, 'multiple' Total
from yourtable t1
where `group` in (select `group`
from yourtable t2
group by `group`
having count(`group`) > 1)
Upvotes: 2