sql - 查询以获取月 postgresql 中最后记录期间的数量

标签 sql postgresql

我已经尝试查询这个问题很久了,所以我放弃了,来到这里寻求您的帮助。真的,伙计们,很多个早上、下午都花在了试图制定这个单一的单一查询上,我几乎失去了理智。无论如何,我会直接与您联系,我们开始吧:

我有一张 table :

     date   | quantity | id
------------+----------+----
 2016-06-10 |      438 | 27
 2016-06-17 |      449 | 28
 2016-06-24 |      458 | 29
 2016-07-01 |      466 | 30
 2016-07-08 |      468 | 31
 2016-07-15 |      468 | 32
 2016-07-22 |      473 | 33
 2016-07-29 |      473 | 34
 2016-08-05 |      475 | 35
 2016-08-12 |      479 | 36
 2016-08-19 |      488 | 37
 2016-08-26 |      498 | 38
 2016-09-02 |      519 | 39

我需要从每个月的最后记录日获取数量。我的意思是,根据上表,我需要以下卷:

     date   | quantity | id
------------+----------+----
 2016-06-24 |      458 | 29
 2016-07-29 |      473 | 34
 2016-08-26 |      498 | 38

我真正需要的决赛 table 是这样的:

     month  | quantity 
------------+----------
         06 |      458
         07 |      473
         06 |      498

我尝试了 GROUP、HAVING、MAX、JOINS、UNIONS 任何你能想象到的东西,买就是无法通过它。有什么想法可以实现这一目标吗?

谢谢

最佳答案

Postgres 有一个很棒的特性叫做distinct on:

select distinct on (date_trunc('month', date)) t.*
from t
order by date_trunc('month', date), date desc;

distinct on 为括号中键的每个值返回一行——在这种情况下,每月一行。哪一排?数据中遇到的第一行。因此,这将返回每个月的最晚日期。

关于sql - 查询以获取月 postgresql 中最后记录期间的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40432464/

相关文章:

postgresql - 如何使用 diesel-rs 选择部分色谱柱?

Django+Postgres : "current transaction is aborted, commands ignored until end of transaction block"

asp.net - SQL Server 2008 在什么数据类型中存储哈希密码

sql - 谷歌云 SQL 第二代 -> "Aborted connection"

sql - SQL中选择该ID存在于另一个表上的数据

ruby-on-rails-3 - 导轨 3 : How to simply test pessimistic locking on console

Postgresql INSERT - 自动获取下一个ID?

mysql - mysql中的内部连接问题

sql - 在同一列上有 FK 和 PK?基数/SQL

perl - DBD::Pg 中的手动事务管理