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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Group by... little problem

Author  Topic 

mirko_fal
Starting Member

2 Posts

Posted - 2011-11-29 : 04:59:22
Hi,
I have a little problem with GROUP BY.
I have this table:

id code
A 1
A 3
B 1
B 2
C 2
C 3

I would like see only the "aggregation" that have code=3 at least once.
If I use GROUP BY (id) I have 3 rows (A, B and C)
But what can I do to see only the rows A and C (which have code=3)?

Thank you very much

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2011-11-29 : 05:02:07
[code]
select t.id, sum(t.code)
from this_table t
where exists
(
select *
from this_table x
where x.id = t.id
and x.code = 3
)
group by t.id
[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2011-11-29 : 05:07:39
SELECT DISTINCT ID WHERE Code = 3


N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

mirko_fal
Starting Member

2 Posts

Posted - 2011-11-29 : 05:48:35
Thank you khtan!!!
You code works perfectly!
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2011-11-29 : 07:15:10
select id, sum(code)
from this_table
group by id
having max(case when code = 3 then 1 else 0 end) = 1



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -