创建具有特殊条件的sql str [英] create sql str with special condition
本文介绍了创建具有特殊条件的sql str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
创建具有特殊条件的sql str
hellow
我有2个表
表a(代码,价格,支票)
表b(代码,百分比)
我想在下面创建一个sql字符串:
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
这个条件必须在sql str中考虑:
And this condition must be consider in sql str:
If (check = 1)
{
New_field = price * percent
}
Else
{
New_field = price * percent * 8
}
现在如何将上述条件放在sql str中?
非常感谢
已添加代码块[/ Edit]
Now how can put above condition in sql str?
Thanks very much
Code block added[/Edit]
推荐答案
您应该搜索 CASE 语句。这基本上是你需要处理你的请求中的条件。
但你的查询有问题:你在表a和b之间进行连接,但是你不要在SELECT部分使用表b。此外,如果您使用的是MS SQL Server,则语法不正确。它应该是:
You should search for CASE statement on MSDN. This is basically what you need to handle conditions in your requests.
But there is something wrong in your query : you make a join between tables a and b, but you don''t use table b in your SELECT part. Moreover, if you are using MS SQL Server, the syntax is incorrect. It should be:
SELECT
a.code
,a.price
,CASE
WHEN (a.check = 1) THEN (a.price * b.percent)
ELSE (a.price * b.percent * 8)
END
AS new_field
FROM a INNER JOIN b ON a.code = b.code
包含CASE声明的更改
[Edit2]用英语替换MSDN链接
Included change with CASE statement
Replaced MSDN link with an english one
这篇关于创建具有特殊条件的sql str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文