Ganeshgm7
Ganeshgm7

Reputation: 455

How to use IF Else in SQL Server

I have to use If Else in Sql Server Query.

Lets Consider the Table below

Product   Kg    Qty    Rate
----------------------------
Mango      1      3      70
Orange     0      2      80
Apple      3      4      90

I need to sum Kg, qty and rate(kgQtyrate) as Total. But when kg is 0 i need to sum only qty*rate.

I need a output like,

Product   Kg    Qty    Rate   Total
-----------------------------------
Mango      1      3      70    210
Orange     0      2      80    160
Apple      3      4      90    1080

How can I use If Else here???

Upvotes: 1

Views: 213

Answers (2)

Saif
Saif

Reputation: 2679

you can use this query

select *, case when kg > 0 
 then  kg + qty + rate 
  else
    qty + rate 
    end as "total" 
from table3

look at attached image

enter image description here

Upvotes: 2

Christos
Christos

Reputation: 53958

You could use CASE:

SELECT 
    *,
    (CASE Kg WHEN 0 THEN 1 ELSE Kg END) * Qty * Rate  AS Total
FROM Products

Please have a look here.

Upvotes: 4

Related Questions