zoukankan      html  css  js  c++  java
  • SQL实现每种产品使用不同算法

    产品表
    产品表ID(主键) 货名           金额         
    1               电视           100
    2               手机           150
    3               衣服           50

    库存表
    库存表ID(主键)        产品表ID         打折                         货存     <-----货存表只有三种状态 0,1,2
    1                       1             0.2                        1
    2                       1             0.3                        1
    3                       2             0.8                        0
    4                       2             0.5                        1
    5                       1             0.7                        1
    6                       3             0.2                        2
    6                       3             0.7                        1
    6                       3             0.1                        0

    我要得到以下结果

    统计
    产品表货名                       赢亏  <----计算                      是否打折       <-----只有三种状态 0,1,2
    电视                100*(1+0.2)*(1+0.3)*(1+0.7)-100=165.2               1          <---当 库存表 的 [货存] 字段全部等于 1 时,那么 [是否打折]=1
    手机                150-(150+150)=-150                                  0          <---当 库存表 的 [货存] 字段有一个为 0, 那么 [是否打折]=0
    衣服                0                                                   2          <---当 库存表 的 [货存] 字段有一个为 2, 那么 [是否打折]=2

    create table #a
    (
     ProductID INT,
     Goods nvarchar(10),
     money int
    )
    insert into #a values(1,'电视',100)
    insert into #a values(2,'手机',150)
    insert into #a values(3,'衣服',50)

    create table #b
    (
     StorageID int,
     ProductID int,
     Discount decimal(10,2),
     ProductStorage int
    )
    insert into #b values(1,1,0.2,1)
    insert into #b values(2,1,0.3,1)
    insert into #b values(3,2,0.8,0)
    insert into #b values(4,2,0.5,1)
    insert into #b values(5,1,0.7,1)
    insert into #b values(6,3,0.2,2)
    insert into #b values(7,3,0.7,1)
    insert into #b values(8,3,0.1,0)

    select
        a.productid, a.goods as 产品表货名,
        盈亏=case when max(b.productstorage)=2 then 0 when min(b.productstorage)=0
     then min(a.money)-sum(a.money)
     else min(a.money)*exp(sum(log(1+b.discount)))-min(a.money) end,
        是否打折=case when max(b.productstorage)=2 then 2 when min(b.productstorage)=0 then 0 else 1 end
    from #a a inner join #b b
    on a.productid=b.productid
    group by a.productid, a.goods

  • 相关阅读:
    2017的结束2018的开始
    .NET Core使用swagger进行API接口文档管理
    数据库可扩展设计方案
    容量估算--随时更新
    分库分表设计基础
    利用bucardo搭建PostgreSQL数据库双活
    通过pgAgent实现PostgreSQL上的自动作业
    MySQL主主配置
    Oracle统计信息不准(谓词越界)造成的性能问题
    获取Oracle中SQL语句的执行计划
  • 原文地址:https://www.cnblogs.com/Ammy/p/1195563.html
Copyright © 2011-2022 走看看