Postgres同月的总和值

时间:2015-05-11 13:17:46

标签: sql postgresql group-by

我正在尝试同月的值之和,但结果是具有日期和值分隔的行。

我的代码是

 select 
    case extract(month from date(m.data)) 
    when extract(month from current_date) then 'Current Month' 
    else to_char(m.data, 'TMMonth/YYYY') end as "Date", 
    sum(m.valor) as "Result" 
    from movimentacao m 
    group by m.data 
    order by m.data;

我的结果是

Apr/2015      | 150.75
Apr/2015      | 15.00
Current Month | 10.00
Current Month | 2.34

我需要的是按月将这些值分组为sum works,但是当我尝试按月分组时sql得到错误,因为我在函数中使用m.data而我需要从m.data分组

2 个答案:

答案 0 :(得分:0)

你不应该GROUP BY m.data(大概是date),而是从你提取的月份开始。然后,您将遇到分组问题,唯一的方法就是按年和月在子查询中进行分组,然后在主查询中重新创建一年中的date和一个月,然后你可以准确输出你所要求的:

SELECT
  CASE
  WHEN extract(year FROM current_date) = yr
   AND extract(month FROM current_date) = mon THEN 'Current month'
  ELSE to_char((yr || '-' || mon || '-01')::date, 'TMMon/YYYY')
  END AS "Date",
  "Result"
FROM (
  SELECT extract(year FROM m.data) AS yr,
         extract(month FROM m.data) AS mon,
         sum(m.valor) AS "Result"
  FROM movimentacao m
  GROUP BY yr, mon) AS sum_by_yr_mon
ORDER by yr, mon;

此查询将按时间顺序排序,即使是多年,也是"当前月份"来了。

答案 1 :(得分:0)

这很好用

select 
   CASE WHEN 
        to_char(event_date, 'MM/YYYY')= to_char(CURRENT_DATE,'MM/YYYY')THEN 'Current Month'
        ELSE to_char(event_date, 'MM/YYYY')
   END as month_year,
sum(m.valor) as "Result" 
from movimentacao m 
group by 1 
order by 1;

与Postgres一起尝试,DEMO