Sql 将Y转换为12%,将N转换为0
折扣表的结果是Y,N。如果Y=12%,如果N=0Sql 将Y转换为12%,将N转换为0,sql,sql-server,tsql,Sql,Sql Server,Tsql,折扣表的结果是Y,N。如果Y=12%,如果N=0 select Product_id, basic_price, cost, discount from prcdpr where strdate = '210319' 我还想在(价格+成本)/折扣上面添加一个公式 我的查询结果 Product_id | basic_price | cost | Discount -------------------------------------------
select
Product_id, basic_price, cost, discount
from prcdpr
where strdate = '210319'
我还想在(价格+成本)/折扣上面添加一个公式
我的查询结果
Product_id | basic_price | cost | Discount
------------------------------------------------------------
998723 | 24 | 18 | Y
992351 | 32 | 25 | N
我对(价格+成本)/折扣的预期结果
Product_id | basic_price | cost | Discount | Price
--------------------------------------------------------------------------
998723 | 24 | 18 | 12% | 37.5
992351 | 32 | 25 | 0 | 57
如果您不完全熟悉T-SQL,则可能需要在查询中使用CASE表达式来推导折扣%值
例如
我更喜欢使用交叉应用来计算这类事情,而不是重复计算并冒着不相同的风险
我不知道你是否真的需要折扣后的百分比符号,但我就是这么做的
declare @PrcDpr table (Product_Id int, Basic_Price money, Cost money, Discount char(1), StrDate varchar(6));
insert into @PrcDpr (Product_Id, Basic_Price, Cost, Discount, StrDate)
values
(998723, 24, 18, 'Y', '210319'),
(992351, 32, 25, 'N', '210319');
select
Product_id, basic_price, cost
, convert(varchar(32),convert(int, X.DiscountRate)) + '%' Discount
, convert(decimal(9,2),(basic_price + cost) * (1.00 - (X.DiscountRate/100.00))) Price
from @PrcDpr
cross apply (values (case when discount = 'Y' then 12.00 else 0.00 end)) X (DiscountRate)
where strdate = '210319';
返回:
产品标识
基本价格
费用
折扣
价格
998723
24
18
12%
36.96
992351
32
25
0%
57
那么,是什么阻止您将公式添加到查询中呢?折扣表是Y和N,我想首先将它们转换为12%和0。但是我不知道怎么做。你试过使用案例吗?您至少可以将公式添加到查询中,然后问题变成如何有条件地应用折扣。将其硬编码为12%可能也是一个糟糕的选择。。。以后肯定会要求您更改它。最好将折扣存储在他们自己的表格中,并在有效的日期范围内。我不明白在给定公式的示例中,你是如何得出37.5的。@Stidgeon,你是对的,示例中的数学计算不完全正确…@DaleK,true。回答EditeDale,一些不错的建议,当然——不过,如果有人还不能在他们的T-SQL中使用CASE,那么表变量和交叉应用程序是相当重要的一步。另外,关于注释2,我们不知道OPs表的完整结构,但“210319”是用于日期比较的有效字符串(在大多数情况下,除了奇怪的排序规则外,SQL很可能将其视为2021年3月19日)。就我个人而言,我倾向于使用“2021-03-19”,但每个都有自己的,当然course@Craig六羟甲基三聚氰胺六甲醚。。。如果您使用的是关系数据库,那么我们假设您熟悉表,所以表变量并不是一个很重要的步骤。我指的不是日期格式,而是存储类型。只需插入一个日期作为不正确的字符串,您就可以在未来几年内将其填满。因此被设计为未来的存储库。。。所以答案不应该针对OP的感知能力。答案应该是给定问题的最佳解决方案。
declare @PrcDpr table (Product_Id int, Basic_Price money, Cost money, Discount char(1), StrDate varchar(6));
insert into @PrcDpr (Product_Id, Basic_Price, Cost, Discount, StrDate)
values
(998723, 24, 18, 'Y', '210319'),
(992351, 32, 25, 'N', '210319');
select
Product_id, basic_price, cost
, convert(varchar(32),convert(int, X.DiscountRate)) + '%' Discount
, convert(decimal(9,2),(basic_price + cost) * (1.00 - (X.DiscountRate/100.00))) Price
from @PrcDpr
cross apply (values (case when discount = 'Y' then 12.00 else 0.00 end)) X (DiscountRate)
where strdate = '210319';