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 |
|
AlphaMeasure
Starting Member
1 Post |
Posted - 2007-05-09 : 21:36:54
|
| I'm trying to write what I intially thought would be an easy SQL statement. I was hoping to get some assistance from some of the pros in this group.Here is my problem (this is a fictious structure).Table IIDColumnIColumnIISample Data:ID State Country1 CO US1 CA US3 GR FR2 CA US1 MA US5 PO GE6 CA US2 MA US8 XO GE2 CO USI want to write some SQL that will select IDs that are in the US and in ALL the states (CA, CO, MA). I would expect ID's 1 and 2 to be returned.I tried writing the statement using an OR, but that doesn't enforce that an ID must be in all the states to be returned. As well as, using AND doesn't work either. I think the answer lies in using IN coupled with embedded Select statements.The actual data is more complicated, using joins, than the example above, but I think if I have the SQL above that I can fill in the blanks.Thanks In Advance!Josh |
|
|
Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)
7020 Posts |
Posted - 2007-05-09 : 22:55:06
|
| [code]select a.IDfrom ( Select aa.ID, State_Count = count(distinct aa.State) from Mytable aa where aa.Country = 'US' group by aa.ID ) a join ( select State_Count = count(distinct bb.State) from MyTable bb where bb.Country = 'US' ) b on a.State_Count = b.State_Count[/code]CODO ERGO SUM |
 |
|
|
|
|
|