在mysql中实现阶梯算法(自定义function)

1.创建两个自定义函数辅助阶梯计算

//计算两个值的最大值
delimiter ;;
create function maxNum(num1 DECIMAL(10,2),num2 DECIMAL(10,2)) returns DECIMAL(10,2)
begin
  return if(num1>=num2,num1,num2);
end;;
delimiter;

//计算两个值的最小值
delimiter ;;
create function minNum(num1 DECIMAL(10,2),num2 DECIMAL(10,2)) returns DECIMAL(10,2)
begin
  return if(num1<=num2,num1,num2);
end;;
delimiter;

2.阶梯核心算法

drop function if exists flushStep;
delimiter ;;
create function flushStep(yearDegree DECIMAL(10,2),degreeNum DECIMAL(10,2),fd int,fu DECIMAL(10,3),sd int ,su decimal(10,3),tu DECIMAL(10,3)) returns VARCHAR(512)
begin
    declare temp_useDgree DECIMAL DEFAULT degreeNum;
    declare useDegree1 DECIMAL DEFAULT minNum(fd-yearDegree,temp_useDgree);
    declare twod int default sd-fd;
    declare fds int default 0;
    declare sds int default 0;
    declare tds int default 0;
    declare maxt DECIMAL DEFAULT 0;
    declare useDegree2  DECIMAL DEFAULT 0;
        declare amount DECIMAL DEFAULT 0;
    if useDegree1>0 THEN 
              set temp_useDgree=temp_useDgree-useDegree1;
                set fds = useDegree1;
        end if;
        set  maxt = maxNum(yearDegree-fd,0);
    set useDegree2 = minNum(twod-maxt,temp_useDgree);
        if useDegree2 >0 THEN
                set temp_useDgree=temp_useDgree-useDegree2;
                set sds = useDegree2;
        end if ;
        if temp_useDgree >0 THEN
                set tds=temp_useDgree;
        end if;
        set  amount= fds*fu+sds*su+tu*tds;
    return concat('{"units":[{"graded":{"name":"G01","displayName":"一阶梯"},"unit":',fu,',"degree":',fds,'},
        {"graded":{"name":"G02","displayName":"二阶梯"},"unit":',su,',"degree":',sds,'},
            {"graded":{"name":"G03","displayName":"三阶梯"},"unit":',tu,',"degree":',tds,'}],"amountFlush":',amount,'}');
 end;;
 delimiter;

3.参数讲解

yearDegree 当年累计用量
degreeNum 本次使用量
fd 一阶梯止度
fu 一阶梯单价
sd 二阶梯止度
su 二阶梯单价
tu 三阶梯单价

4.运行示例

输入参数:200,100,250,1,280,2,3

输出:
{
    "units":[
        {
            "graded":{
                "name":"G01",
                "displayName":"一阶梯"
            },
            "unit":1,
            "degree":50
        },
        {
            "graded":{
                "name":"G02",
                "displayName":"二阶梯"
            },
            "unit":2,
            "degree":30
        },
        {
            "graded":{
                "name":"G03",
                "displayName":"三阶梯"
            },
            "unit":3,
            "degree":20
        }
    ],
    "amountFlush":170
}

你可能感兴趣的:(在mysql中实现阶梯算法(自定义function))