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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 simple IF ELSE help

Author  Topic 

nilaavu
Starting Member

18 Posts

Posted - 2009-06-09 : 13:00:00
How do i do the If statement in the following query....I cant work it out...can u please help?

SELECT

IF Column1 > 0

Column1 as Amount

ELSE IF Column2 > 0

Column2 as Amount

ELSE IF Column3>0

Column 3 as Amount

ELSE

0 as Amount,

myDate, myID

FROM myTable

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-06-09 : 13:05:25
select
case
when column1 > 0 then column1
when column2 > 0 then column2
when column3 > 0 then column3
else 0
end as Amount,
myDate,
myID
from table


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-06-09 : 13:14:55
[code]SELECT COALESCE(NULLIF(Column1,0),NULLIF(Column2,0),NULLIF(Column3,0),0) as Amount,
myDate, myID
FROM myTable
[/code]
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-06-09 : 13:45:38
quote:
Originally posted by visakh16

SELECT COALESCE(NULLIF(Column1,0),NULLIF(Column2,0),NULLIF(Column3,0),0) as Amount, 
myDate, myID
FROM myTable



I knew this solution will be posted here!
But I have not provided this solution because Column1 could be -1 for example.

Greetings
Webfred


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-06-09 : 13:48:38
quote:
Originally posted by webfred

quote:
Originally posted by visakh16

SELECT COALESCE(NULLIF(Column1,0),NULLIF(Column2,0),NULLIF(Column3,0),0) as Amount, 
myDate, myID
FROM myTable



I knew this solution will be posted here!
But I have not provided this solution because Column1 could be -1 for example.

Greetings
Webfred


No, you're never too old to Yak'n'Roll if you're too young to die.


i have thought about that..but we dont know how actual data is. so lets wait until we hear back from OP
Go to Top of Page

nilaavu
Starting Member

18 Posts

Posted - 2009-06-09 : 16:32:32
Thank you guys...
The Amount can be -1 as it could be a debit or credit.

Thanks again...
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-06-09 : 16:44:11
welcome


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page
   

- Advertisement -