sql-server - Conditions in T-SQL Query
问题描述
A table named Fruit
has columns ID
, Fruit name
and Cost
and New Cost
:
|ID | Fruit Name | Cost | New Cost
+---+------------+------+---------
| 1 | Apple | 10 | 9
| 2 | Banana | 20 | 22
| 3 | Orange | 33 | 33
I wish to query this table under one condition. If New Cost is more than Cost then Final Cost should be 0.9*Cost else Final Cost should be New Cost.
Output should look like:
| ID | Fruit Name | Final Cost
+----+------------+-----------
| 1 | Apple | 9
| 2 | Banana | 18
| 3 | Orange | 29.7
Unfortunately, I am not able to apply If condition in SQL query. Is there any way to achieve this??
解决方案
Please check this answer
DECLARE @table TABLE
(
ID INT IDENTITY(1,1) PRIMARY KEy,
FruteName NVARCHAR(200),
Cost DECIMAL(10,2),
NewCost DECIMAL(10,2)
)
INSERT INTO @table VALUES('Apple','10',9),('Banana','20',22),('Orange','33',33)
SELECT *, IIF(NewCost>=Cost,(Cost*0.9),NewCost) AS FinalCost
FROM @table
推荐阅读
- scikit-learn - 从 sklearn 导入困难
- python - 如何在 Python 中将任意长度的位序列转换为有符号或无符号整数?
- css - Fullpage.js 和 fp-auto-height-responsive 错误
- java - git 宕机时的后备资源,同时启动配置服务器本身
- python - 如何切换窗口保持在顶部提示
- bash - 多个配对文件的 for 循环
- android - 使用列表适配器向回收站视图提交一个全新的列表会导致闪烁/滞后的动画
- django - 表单中的 CreateWithInlinesView 验证
- javascript - 为什么我收到错误 data.findIndex is not a function in React with Redux 项目?
- python - Blit 功能不起作用,循环会很快吗?