SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Need help with inserting a Case statement
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

tlk072107
Starting Member

4 Posts

Posted - 11/06/2012 :  12:35:03  Show Profile  Reply with Quote
I am relatively new to SQL but learning, I currently have a lengthy query which selects data from 6 different tables that have been joined as needed.

I have two more columns I need to add to my result, which I believe would employ a case statement but after some research on my own I have not found the answer.

I have a table which includes many columns, two of which are Location and ID. I need to add a statement that will put a column in my results, which would have the following:

1st colummn:

If there are more than one records found with the same Location/ID combination, return nothing..

If there is only one record found with the same Location/ID combination, return the Location value.

2nd column:

If there were more than one records found in the previous query, return the count of the number of records that met the criteria.

If it was only one found in the previous query, return nothing here.



Not sure how well I am outlining the requirement - but I have been reading up on case statements and this kind of scenario has still given me trouble....any help is appreciated.

Thanks!

TG
Flowing Fount of Yak Knowledge

USA
6059 Posts

Posted - 11/06/2012 :  13:38:16  Show Profile  Reply with Quote
I am assuming based on your explanation that you will only have one row returned per location/ID value. And if that is the case I also assume that you are GROUPing by Location and ID. If all that is true then perhaps something like this:

select location
       ,id
       ,case when count(*) = 1 then location else null end as Col1
       ,case when count(*) > 1 then count(*) else null end as Col2
from   <yourTables>
group by location
       ,id


Be One with the Optimizer
TG
Go to Top of Page

tlk072107
Starting Member

4 Posts

Posted - 11/06/2012 :  14:22:13  Show Profile  Reply with Quote
That works perfectly, and your assumptions were correct. Thank you
Go to Top of Page

TG
Flowing Fount of Yak Knowledge

USA
6059 Posts

Posted - 11/06/2012 :  15:18:17  Show Profile  Reply with Quote
Cool - you're welcome

Be One with the Optimizer
TG
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000