PostgreSQL查询:每月最新可用日期的列总和

时间:2017-08-16 08:37:38

标签: postgresql

给出一个如下所示的pSQL表:

date       | data
2015-01-29 | 5
2015-02-28 | 13
2015-05-16 | 1

如何获取每个月最后一个可用日期的数据总和? 示例结果:

SELECT year,month,max(day),sum(data) FROM
  (
    SELECT
      date,
      date_part('year', date)  AS year,
      date_part('month', date) AS month,
      date_part('day', date)   AS day,
      sum(data)                AS tdata
    FROM table a
    GROUP BY date, date_part('year', date), date_part('month', date), date_part('day', date)
    ORDER BY year ASC, month ASC, day ASC
  ) dataq
GROUP BY year,month

这是我到目前为止所尝试的:

<div class="col-md-6 col-sm-6 textbox">
   <div class="row">
      <div class="col-md-7 col-sm-6">
          <img src="">
      </div>
      <div class="col-md-5 col-sm-6">
          <p>Text goes here.....</p>
          <p>ddescription goes here</p>
      </div>
   </div>
</div>

我从中获得的总和似乎是错误的。

2 个答案:

答案 0 :(得分:1)

我想你只需要删除你不想总结的日子。例如,使用NOT EXISTS如下:

SELECT year,month,max(day),sum(tdata) tdata FROM
  (
    SELECT
      d,
      date_part('year', d)  AS year,
      date_part('month', d) AS month,
      date_part('day', d)   AS day,
      sum(data)                AS tdata
    FROM tab a
    WHERE NOT EXISTS 
    (
      SELECT *
      FROM tab a2
      WHERE date_part('year', a.d) = date_part('year', a2.d) AND
          date_part('month', a.d) = date_part('month', a2.d) AND
          date_part('day', a.d) < date_part('day', a2.d)
    )
    GROUP BY d, date_part('year', d), date_part('month', d), date_part('day', d)
    ORDER BY year ASC, month ASC, day ASC
  ) dataq
GROUP BY year,month

SQLFiddle

答案 1 :(得分:1)

您应该计算内部查询中的总和,按一天分组。在外部查询中选择最新的一天:

select distinct on (year, month) 
    make_date(year::int, month::int, day::int) as date, 
    data
from (
    select 
        date_part('year', date) as year,
        date_part('month', date) as month,
        date_part('day', date) as day,
        sum(data) as data
    from my_table
    group by date
    ) s
order by year, month, day desc

    date    | data 
------------+------
 2015-01-29 |    5
 2015-02-28 |   13
 2015-05-16 |    1
(3 rows)