Postgres复杂的查询生成case语句

时间:2017-06-04 23:14:05

标签: sql postgresql

我有这样的查询:

select date, meter,
   sum(case when period = 1 then round(value, 2)end) as period_01,
   sum(case when period = 2 then round(value, 2)end) as period_02,
   sum(case when period = 3 then round(value, 2)end) as period_03,
   sum(case when period = 4 then round(value, 2)end) as period_04,
   sum(round(kwh, 2)) as total
from table
group by date, meter
order by date, meter;

我需要做一些事情:

  1. 总列需要是case语句的总和。因为案例陈述是四舍五入的,所以总数是错误的。

  2. 是否可以根据任何给定日期的周期数生成case语句列?例如根据每天的周期数看起来像这样

  3. Date - MeterId - Periods . . . - Total    
    2017-06-05 | meter_01 | 10 | 14 | 6 | {total} 30
    2017-06-06 | meter_01 | 10 | 7  | 2 | 5 | {total} 24
    

    我想它必须首先找到每个日期有多少个句点然后运行查询但这超出了我的知识水平...

1 个答案:

答案 0 :(得分:0)

第一个问题的答案是在round()之后sum()

select date, meter,
       round(sum(case when period = 1 then value end), 2) as period_01,
       round(sum(case when period = 2 then value end), 2) as period_02,
       round(sum(case when period = 3 then value end), 2) as period_03,
       round(sum(case when period = 4 then value end), 2) as period_04
       round(sum(kwh), 2) as total
from table
group by date, meter
order by date, meter;

第二个问题的答案基本上“不容易”。您可以将动态SQL crosstab()与非常复杂的表达式一起使用,或将值放入数组/ json对象中。但是没有简单的方法来返回可变数量的列。