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 |
|
torlok2002
Starting Member
11 Posts |
Posted - 2009-04-22 : 15:52:53
|
| I'm trying to query a table and return a result if the account has a cpt code like 93510%, but it to be dropped off the query if it also has a cpt code like 93543%. Any ideas on how to approach this? I'm still drawing blanks. Here is my query so far to get the following outputselect distinct account, cpt from table where (cpt like'93510%' or cpt like '93543%') and company='MAIN'Account cpt-----------------213787 93510213787 93543213787 935102685482 935102685482 93543190986 9351026190986 9354382573 935102682573 93543213771 9351026213771 935433269 93510263269 93543300139 9351026300139 93543207055 9354394009 935102694009 93543 |
|
|
nr
SQLTeam MVY
12543 Posts |
Posted - 2009-04-22 : 15:58:41
|
| select distinct account, cpt from tablewhere cpt like'93510%'and company='MAIN'and account in (select account fom table where (cpt like'93510%' or cpt like '93543%')and company='MAIN'group by account having max(left(cpt,5)) = '93510'==========================================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. |
 |
|
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2009-04-22 : 16:05:41
|
Here are a couple of ways to do it depending on the size of your data: SELECT A.*FROM ( select distinct account, cpt from table where cpt like'93510%' and company='MAIN' ) AS ALEFT OUTER JOIN ( select distinct account from table where cpt like'93543%' and company='MAIN' ) AS B ON A.account = B.AccountWHERE B.Account IS NULL select distinct account, cpt from table where cpt like'93510%' and company='MAIN' AND account NOT IN (SELECT DISTINCT account FROM table WHERE cpt like'93543%' and company='MAIN') |
 |
|
|
torlok2002
Starting Member
11 Posts |
Posted - 2009-04-23 : 16:38:29
|
| Great, after a bit of massaging I was able to make it work! Thanks a ton. Never used NOT IN before. |
 |
|
|
Qualis
Posting Yak Master
145 Posts |
Posted - 2009-04-23 : 16:43:14
|
Please do not EVER use Not In with a sub-select. It can have disastrous results on performance. Not In is appropriate for small lists like:Select ColorName From MyColorsWhere ColorName Not In ('Red', 'Green', 'Salmon') |
 |
|
|
|
|
|