【问题标题】:Electricity Bill tariff slab calculation using SQL使用 SQL 计算电费单价板
【发布时间】:2020-03-30 11:11:47
【问题描述】:

我的“读数”表具有以下架构:

----------------------------------------
|  Id  |        DateTime     |  value  |
---------------------------------------
|  16  |  01/01/19  22:50:59 |    90   | 
---------------------------------------
|  16  |  01/02/19  8:53:11  |    200  | 
---------------------------------------
|  16  |  04/01/19  22:50:59 |    400  |  
---------------------------------------
|  16  |  03/01/19  1:20:00  |    100  |
---------------------------------------

另一个表“关税”具有以下架构:

-------------------------------------------------
|  Id  |   start_value  | end_value |    rate   |
-------------------------------------------------
|  16  |        0       |    100    |    0.2    | 
-------------------------------------------------
|  16  |       100      |    500    |    0.25   | 
------------------------------------------------
|  16  |       500      |    1000   |    0.3    |   
-------------------------------------------------

我想在这里获得总成本作为示例: 值的总和为 = 90 + 200 + 400 + 100 = 790 根据关税表,总和的前100个将乘以0.2,其他400个将乘以0.25 ...

Then the cost = (100 * 0.2) + (400 * 0.25) + (290 * 0.3) = 207

【问题讨论】:

    标签: sql postgresql join group-by sum


    【解决方案1】:

    我认为这是一个join 和聚合:

    select sum(value * rate)
    from readings r join
         tariffs t
         on r.id = t.id and
            r.value >= t.start_value and
            r.value < t.end_value;
    

    编辑:

    哦,我明白了。你需要这个基于总和:

    select sum(t.rate *
               greatest(least(sum_value, t.end_value) - greatest(sum_value, t.start_value), 0)
              )
    from (select r.id, sum(value) as sum_value
          from readings r
         ) r join
         tariffs t
         on r.id = t.id 
    

    【讨论】:

    • @MohammadBahja 。 . .您是否有理由不接受此答案?
    • 对不起,测试后它对我不起作用,但下面的查询可以正常工作
    【解决方案2】:

    最后我通过下面的查询解决了

    select sum(case when sum_value - end_value >= 0 then (end_value - start_value) * rate when sum_value - start_value >= 0 then (sum_value - start_value) * rate  else 0 end)
    from (
            select sum(value) as sum_value, tariffs.rate as rate, tariffs.end_value as 
            end_value, tariffs.start_value as start_value
            from readings
            join
            tariffs
            on readings.id = tariffs.id
            group by rate, end_value, start_value
         ) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多