Sql 如果列值为X,则计算百分比
我有一个表,下面有列:Sql 如果列值为X,则计算百分比,sql,percentage,calculation,Sql,Percentage,Calculation,我有一个表,下面有列: 成本 销售渠道 产品销售商 如果满足某些值,我想对成本进行不同的计算 i、 e if Sales Channel = Mobile, and Product Seller = Mark, then take 8% off cost if sales channel = desktop, and product seller = James, then take 5% off cost 我试过: select channel, acct_mgmr, cost (co
- 成本
- 销售渠道
- 产品销售商
if Sales Channel = Mobile, and Product Seller = Mark, then take 8% off cost
if sales channel = desktop, and product seller = James, then take 5% off cost
我试过:
select
channel,
acct_mgmr,
cost
(cost*0.05) as A
(cost*0.08) as B
from db.table
理想情况下,能够根据渠道和销售经理查看最终销售价格…值根据列的组合而变化您可以使用
案例
调整每个用例的计算:
SELECT
channel,
acct_mgmr,
CASE
WHEN ( Sales_Channel = 'Mobile' AND Product_Seller = 'Mark' ) THEN cost * 0.92
WHEN ( Sales_Channel = 'desktop' AND Product_Seller = 'James') THEN cost * 0.95
ELSE cost
END as new_cost
FROM mytable
您可以使用
CASE
语句执行类似的操作
CREATE TABLE #tmp (Channel VARCHAR(255), acct_mgmr VARCHAR(255), cost INT)
INSERT INTO #tmp VALUES ('Mobile', 'Mark', 100)
INSERT INTO #tmp VALUES ('desktop', 'James', 200)
SELECT
channel,
acct_mgmr,
cost,
cost * (1 - CASE
WHEN Channel = 'Mobile' AND acct_mgmr = 'Mark' THEN 0.08
WHEN Channel = 'Desktop' AND acct_mgmr = 'James' THEN 0.05
END
) AS ModifiedCost
FROM #tmp
DROP TABLE #tmp
我一点也不懂。请提供一些示例数据并显示预期结果。