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 |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2006-05-03 : 08:08:04
|
| bhmet writes "I group records by account number. Then I want to look at ALL records in the group to make sure a condition does NOT exist in the entire group.I couldn't find any way to do this other than counting within the group each time the undesired condition DOES exist.ExampleAcct no code1 2 1 61 51 9I want to select accountno when there is no '9' code in the group. The above example should not be selected.So I've coded:Select count(code) as code_ct,accountno from table1 whereCode = '9'group by accountnohaving count(code_ct) = 0 I always get 0 recs returned, but when I codehave count(code_ct) = 1I get the right result. In fact if I code any number other than 0, I get the right result." |
|
|
nr
SQLTeam MVY
12543 Posts |
Posted - 2006-05-03 : 09:07:06
|
| having count(code_ct) = 0 means give me all groups with no rows so you will never get anything.having max(case when code_ct = 9 then 1 else 0 end) = 1And I guess you want how many codes there are soSelect count(code) as code_ct,accountno from table1group by accountnohaving max(case when code_ct = 9 then 1 else 0 end) = 1==========================================Cursors are useful if you don't know sql.DTS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
|
RyanRandall
Master Smack Fu Yak Hacker
1074 Posts |
Posted - 2006-05-03 : 10:24:43
|
Hi bhmet,It's hard to understand exactly what you're after without more example data and an example result. Maybe Nigel has what you need, and maybe you're after something more like this...--datadeclare @t table (AcctNo int, code int)insert @t select 1, 2union all select 1, 6union all select 1, 5union all select 1, 9union all select 2, 1union all select 2, 2union all select 2, 5--calculationselect * from @t where AcctNo not in (select AcctNo from @t where code = 9) Ryan Randallwww.monsoonmalabar.com London-based IT consultancy Solutions are easy. Understanding the problem, now, that's the hard part. |
 |
|
|
|
|
|
|
|