如何在SQL中使用带多个条件的嵌套大小写
如何修改下面的sql脚本以计算以下条件如何在SQL中使用带多个条件的嵌套大小写,sql,sql-server,sql-server-2014,Sql,Sql Server,Sql Server 2014,如何修改下面的sql脚本以计算以下条件 如果LPO为空或不为空,则在2018年1月1日至2018年3月31日之间的发行日期,总含税将为数量x单价加5% 2018年3月31日之后,当LPO不为空时,数量x单价不应增加5%,否则增加5% 它如何处理嵌套的case或建议任何其他方式 我的桌子: +------------+-----+------------+---------------+ | Issue_date | qty | unit_price | LPO | +
- 如果LPO为空或不为空,则在2018年1月1日至2018年3月31日之间的发行日期,总含税将为数量x单价加5%
- 2018年3月31日之后,当LPO不为空时,数量x单价不应增加5%,否则增加5% 它如何处理嵌套的case或建议任何其他方式
+------------+-----+------------+---------------+
| 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
根据你的逻辑,你可以试试这个
或
和
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
一个计算选项是:
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;
您可以使用以下功能:
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
需要将数量*LPO替换为数量*单价和(或LPO为空)
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