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 |
tlk072107
Starting Member
4 Posts |
Posted - 2012-11-06 : 12:35:03
|
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
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2012-11-06 : 13:38:16
|
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 Col2from <yourTables>group by location ,id Be One with the OptimizerTG |
|
|
tlk072107
Starting Member
4 Posts |
Posted - 2012-11-06 : 14:22:13
|
That works perfectly, and your assumptions were correct. Thank you |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2012-11-06 : 15:18:17
|
Cool - you're welcomeBe One with the OptimizerTG |
|
|
|
|
|
|
|