March 22, 2013 at 11:05 am
create sql str with special condition
hellow
I have 2 table
Table a(code, price, check)
Table b(code, percent)
I want to create a sql string such below:
Select a.code, a.price, (price * percent) as new_field
From a,b
Where a.code = b.code
And this condition must be consider in sql str:
If (check = 1)
{
New_field = price * percent
}
Else
{
New_field = price * percent * 8
}
Now how can put above condition in sql str?
Thanks very much
March 22, 2013 at 11:09 am
are you familiar with the CASE statement yet? it's what you need to add to your query to do what you are asking.
Other suggestions: don't use the Old syntax Table1,Table2
1. use the explicit INNER JOIN instead.
2. don't name your columns with reserved word(percent,check)
SELECT
a.code,
a.price,
( price * [percent] ) AS new_field,
CASE
WHEN [check] = 1
THEN price * [percent]
ELSE price * [percent] * 8
END AS ReallyNewField
FROM a
INNER JOIN b
ON a.code = b.code
Lowell
March 22, 2013 at 11:12 am
Try this:
select
a.code,
a.price,
new_field = a.price * b.percent * case when a.check = 1 then 8 else 1 end
from
a
inner join b
on (a.code = b.code);
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply