如何修改以下sql脚本以计算以下条件
在2018年3月31日之后,当LPO不为NULL时,不应将 qty x unit_price 添加5%,否则应添加5%。
它如何与嵌套大小写一起工作或建议其他方式。
我的表格:
+------------+-----+------------+---------------+
| Issue_date | qty | unit_price | LPO |
+------------+-----+------------+---------------+
| 10-Jan-18 | 1 | 42 | 1-2018-001166 |
| 12-Jan-18 | 1 | 100 | NULL |
| 20-Sep-18 | 1 | 25 | NULL |
| 15-Oct-18 | 2 | 12 | 1-2018-002233 |
| 20-Oct-18 | 1 | 100 | 1-2018-002233 |
+------------+-----+------------+---------------+
SELECT Qty,unit_price,LPO,
case
when issue_date <= '2018-03-31' and issue_date >= '2018-01-01'
then (((qty) *(unit_price)) * 1.05 )
else
(((qty) *(unit_price)) * 1.05 )
end as Tot_inc_Tax
from My_Table
预期结果
+------------+-----+------------+---------------+---------------+
| Issue_date | qty | unit_price | LPO | Total_Inc_Tax |
+------------+-----+------------+---------------+---------------+
| 10-Jan-18 | 1 | 42 | 1-2018-001166 | 44.1 |
| 12-Jan-18 | 1 | 100 | NULL | 105 |
| 20-Sep-18 | 1 | 25 | NULL | 26.25 |
| 15-Oct-18 | 2 | 12 | 1-2018-002233 | 24 |
| 20-Oct-18 | 1 | 100 | 1-2018-002233 | 100 |
+------------+-----+------------+---------------+---------------+
答案 0 :(得分:1)
根据您的逻辑,您可以尝试
第一个使用OR
第二次使用AND
并确保所有内容都符合您的逻辑。
SELECT Issue_date,Qty,unit_price,LPO,
case
when (issue_date BETWEEN '2018-01-01' AND '2018-06-30') OR unit_price IS NULL
THEN qty *LPO * 1.05
when issue_date > '2018-03-31' AND unit_price IS NOT NULL
THEN qty * LPO END 'Total_Inc_Tax'
from My_Table
答案 1 :(得分:1)
一个计算选项为:
with my_table(Issue_date, qty, unit_price, LPO) as
(
select '2018-01-10',1,42 ,'1-2018-001166' union all
select '2018-01-12',1,100,NULL union all
select '2018-09-20',1,25 ,NULL union all
select '2018-10-15',2,12 ,'1-2018-002233' union all
select '2018-10-20',1,100,'1-2018-002233'
)
select Qty,unit_price,LPO,
(case
when issue_date between '2018-01-01' and '2018-03-31'
then (((qty) *(unit_price)) * 1.05 )
when issue_date > '2018-03-31' then
( case when lpo is null then
(((qty) *(unit_price)) * 1.05 )
else
(((qty) *(unit_price)))
end )
end ) as Tot_inc_Tax
from My_Table;
答案 2 :(得分:0)
您可以使用:
SELECT Qty,unit_price,LPO,
case
when issue_date between '2018-01-01' and '2018-03-31'
then (((qty) *(unit_price)) * 1.05 )
else when issue_date > '2018-03-31' and LPO is null
(((qty) *(unit_price)) * 1.05 )
end as Tot_inc_Tax
from My_Table