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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help with SQL Query - Case & Union

Author  Topic 

its_me
Starting Member

6 Posts

Posted - 2012-10-12 : 13:34:20
Here is the description of my sql problem:

select distinct A, B, C
case when v.A is null THEN 'No' else 'Yes' END AS Exists_In_V,
case when '' is null THEN 'No' END AS Exists_As_C
some inner joins ….
from someTable
union
select distinct A, B, C
case when '' is null THEN 'No' END AS Exists_In_V,
case when X is null THEN 'No' else 'Yes' END AS Exists_As_C
some inner joins
from someTable1

If both the queries find a result, the data is returned is in two rows. For EX:
Col1 Col2 Col3 Exists in V Exists_As_C
A B C Yes No
A B C No Yes

Is there a way I get only 1 result record as:

Col1 Col2 Col3 Exists in V Exists_As_C
A B C Yes Yes

I first had my query without the union, because if the value is not present in one of the tables, nothing is returned. I had something like this before:

select distinct A, B, C
case when v.A is null THEN 'No' else 'Yes' END AS Exists_In_V,
case when X is null THEN 'No' else 'Yes' END AS Exists_As_C
from someTable
inner join …
and v.something = ‘xya’
left join X
and x.AC = ‘xya’


sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-10-12 : 14:22:54
Since you have only pseudo-code that I cannot parse, I am not able to completely follow the logic. With my limited understanding, something like this may be what you need:
SELECT
COALESCE(t1.A,t2.A) AS A,
COALESCE(t1.B,t2.B) AS B,
COALESCE(t1.C,t2.C) AS C,
CASE WHEN t1.A IS NOT NULL THEN 'Yes' ELSE 'No' END AS Exists_In_V,
CASE WHEN t2.X IS NOT NULL THEN 'Yes' ELSE 'No' END AS Exists_As_C
FROM
someTable t1
FULL JOIN someTable t2 ON
.....
Go to Top of Page

its_me
Starting Member

6 Posts

Posted - 2012-10-12 : 14:44:02
Hi Sunitabeck,

I just mailed you the complete query I am working with. Thanks for the response!

Thanks!
Go to Top of Page
   

- Advertisement -