all groups > sql server programming > april 2007 >
You're in the

sql server programming

group:

Need help in a query


Need help in a query SqlBeginner
4/24/2007 5:18:02 PM
sql server programming: Hi All,

This is my existing query and i have given below the output sample as well.
btw I am using SQL Server 2005.

Select field1, field2, Sum(A) as A, Sum(B) As B,
'1 : ' + convert(varchar(20),convert(decimal(8,2),NULLIF(sum(B),0)) /
convert(decimal(8,2),NULLIF(sum(A),0))) as C
From
(
Subquery comes here
) As z
Group by field1, field2
Order by field1, field2

Current Output:
----------------
Column1 column2 A B C
aaa bbb 10 20 1:2
aa1 bb1 20 40 1:2
....
....
xyz abc 10 0 NULL

But where ever C is NULL i want to automatically display A:B i.e.,

Expected Output:
----------------
Column1 column2 A B C
aaa bbb 10 20 1:2
aa1 bb1 20 40 1:2
....
....
xyz abc 10 0 10:0

Can anyone help me in this?

Regards
Re: Need help in a query SqlBeginner
4/24/2007 8:54:01 PM
Hi,

Can you tell me how to make use of Coalesce to get that result.

Expected Output:
----------------
Column1 column2 A B C
aaa bbb 10 20 1:2
aa1 bb1 20 40 1:2
...
...
xyz abc 10 0 10:0

Regards
Pradeep

[quoted text, click to view]
Re: Need help in a query Kamran
4/24/2007 10:33:43 PM
Hi

You can use COALESCE.

Regards,

Kamran

[quoted text, click to view]

Re: Need help in a query Kamran
4/25/2007 12:26:09 AM
Hi,

See if you can use 'Coalesce' like following (untested):
--
Coalesce('1 : ' + convert(varchar(20),convert(decimal(8,2),NULLIF(sum(B),0))
/
convert(decimal(8,2),NULLIF(sum(A),0))), cast(A as varchar) + ':' + cast(B
as varchar))
--

Kamran

[quoted text, click to view]

Re: Need help in a query Vadivel
4/25/2007 9:36:01 AM
No it didn't work.

[quoted text, click to view]
Re: Need help in a query Vadivel
4/25/2007 11:00:03 AM
Yes Coalesce can be used here. Check the syntax and try out.

another quick solution is to make use of Case when statement.
case when b=0 then cast(a as varchar(5)) + ':'+ cast(b as varchar(5) else
begin ---- do whtver here---- end

Regards
Vadivel

http://vadivel.blogspot.com


[quoted text, click to view]
AddThis Social Bookmark Button