计算销售价格至少达到10%的利润

时间:2015-03-20 10:54:11

标签: sql sql-server tsql

我需要在SQL查询中运行循环。我的查询会查看[PROFIT_MARGIN]以确保%PROFIT高于10%(在本例中)。

但有些数字低于10或产生负数,所以我需要提高价格,直到[PROFIT_MARGIN]达到更有利的点。

SELECT [RRP], [COST], [PROFIT], ([PROFIT/RRP]*100) AS [PROFIT_MARGIN],
       CASE WHEN ([PROFIT/RRP]*100) > 10 
            THEN RRP
            ****** OH NO THE PROFIT IS LESS THAN 10, WE NEED TO INCREASE THE RRP UNTIL SUCH A POINT THAT THE PROFIT_MARGIN is EQUAL to 10 THEN SET THE PRICE TO THAT NEW FIGURE ******
       END AS [PRICE]
FROM SOME_TABLE

一些示例数据

RRP   Cost   Profit  Profit Margin
25    8      17      68
5.95  7.08   -1.13   -18.9915966387
17    13.02  3.98    23.4117647059
1.85  4.57   -2.72  -147.027027027
2.3   4.74   -2.44   -106.0869565217
2.65  5.02   -2.37   -89.4339622642

我的猜测是,我需要人为地增加[RRP],直到结束[PROFIT_MARGIN]列点击10%为止。

我的方法,对循环的要求可能是错的,我不是SQL Pro。

2 个答案:

答案 0 :(得分:3)

你不需要为这种性质的东西使用循环。

您的基本检查要求利润至少为10%,因此您只需检查利润率是否为< 10%,否则增加售价。

以下是一个包​​含上述数据的示例,您可以按原样执行:

CREATE TABLE #SOME_TABLE
    (
      [RRP] NUMERIC ,
      [Cost] NUMERIC ,
      [Profit] NUMERIC ,
      [Profit_Margin] NUMERIC
    );

INSERT  INTO #SOME_TABLE
        ( [RRP], [Cost], [Profit], [Profit_Margin] )
VALUES  ( 25, 8, 17, 68 ),
        ( 5.95, 7.08, -1.13, -18.9915966387 ),
        ( 17, 13.02, 3.98, 23.4117647059 ),
        ( 1.85, 4.57, -2.72, -147.027027027 ),
        ( 2.3, 4.74, -2.44, -106.0869565217 ),
        ( 2.65, 5.02, -2.37, -89.4339622642 );

DECLARE @MinProfitMargin INT = 10

SELECT  RRP ,
        Cost ,
        Profit ,
        Profit_Margin ,
        CASE WHEN Profit_Margin < @MinProfitMargin 
             THEN Cost * 1.1
             ELSE RRP
        END AS RRPor10PercentProfit
FROM    #SOME_TABLE

DROP TABLE #SOME_TABLE

输出:

RRP Cost    Profit  Profit_Margin   RRPor10PercentProfit
25  8       17      68              25.0
6   7       -1      -19             7.7
17  13      4       23              17.0
2   5       -3      -147            5.5
2   5       -2      -106            5.5
3   5       -2      -89             5.5

最后一栏RRPor10PercentProfit显示当前RRP是否达到至少10%的利润,否则会显示达到10%利润所需的价值。这在代码的这一部分计算:

-- is the Profit_Margin less than my variable (10%)
CASE WHEN Profit_Margin < @MinProfitMargin 
     -- if so add 10% to cost price
     THEN Cost * 1.1
     -- otherwise give me the RRP
     ELSE RRP
END AS RRPor10PercentProfit

答案 1 :(得分:3)

请阅读我对该问题的评论,并查看Tanner提供的解决方案。

因此,如果您要更新RRP,请使用UPDATE声明:

UPDATE t1 SET [RRP] = t2.[COST] *1.1
FROM tableName t1 INNER JOIN tableName t2 ON t1.PKey = t2.PKey
WHERE (t1.[RRP]/t1.[COST]) < 1.1 

感谢Tanner,感谢您的宝贵意见;)