Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
hai
Yak Posting Veteran
84 Posts |
Posted - 2009-05-11 : 16:46:57
|
declare @tbl1 table (id int, base char(1))insert into @tbl1 (id, base)select 1, 'a'union allselect 1, 'b'union allselect 2, 'a'union allselect 2, 'c'union allselect 3, 'b'union allselect 3, 'a'select a.id from @tbl1 ainner join (select id, count(id) bcount from @tbl1 where base in ('b') group by id)bon a.id=b.idwhere bcount > 0 and base in ('a')group by a.idhaving count(a.id) > 0With the sample above, can this be rewritten differently? I trying to find which id have both 'A' and 'B' as the based.thanks |
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2009-05-11 : 17:09:27
|
You could do this:SELECT a.idFROM @tbl1 AS AINNER JOIN@tbl1 AS BON A.id = B.idAND A.base = 'a'AND B.base = 'b' If you have a case where you would have one ID with multiple a's and b's, you could add a DISTINCT to the SELECT clause. |
|
|
hai
Yak Posting Veteran
84 Posts |
Posted - 2009-05-12 : 08:53:49
|
Thank you very much... |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2009-05-12 : 09:26:24
|
orselect id from @tbl1 group by id having sum(case when base='a' then 1 else 0 end+case when base='b' then 1 else 0 end)=2MadhivananFailing to plan is Planning to fail |
|
|
hai
Yak Posting Veteran
84 Posts |
Posted - 2009-05-12 : 13:01:33
|
declare @tbl1 table (id int, base char(1))insert into @tbl1 (id, base)select 1, 'a'union allselect 1, 'b'union allselect 1, 'b'union allselect 2, 'a'union allselect 2, 'c'union allselect 3, 'b'union allselect 3, 'a'union allselect 4, 'b'union allselect 4, 'b'SELECT distinct a.idFROM @tbl1 AS AINNER JOIN@tbl1 AS BON A.id = B.idAND A.base = 'a'AND B.base = 'b'select id from @tbl1group by idhaving sum(case when base='a' then 1 else 0 end+case when base='b' then 1 else 0 end)=2your code doesn't work Madhivanan. |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2009-05-14 : 01:50:35
|
Ok. It should then beselect id from @tbl1where base in ('a','b')group by idhaving count(distinct(base))=2MadhivananFailing to plan is Planning to fail |
|
|
|
|
|
|
|