Sql 查询获取每月的最后一个日期

Sql 查询获取每月的最后一个日期,sql,postgresql,Sql,Postgresql,我有一张这样的桌子 日期 数量 2021-01-01 100 2021-01-15 200 2021-01-31 300 2021-02-01 400 2021-02-15 500 2021-02-28 600 2021-03-01 700 2021-03-02 800 2021-03-03 900 要查找组的最新记录,您可以在上使用DISTINCT: SELECT DISTINCT ON (date_trunc('month', my_date)) * FROM mytable OR

我有一张这样的桌子

日期 数量 2021-01-01 100 2021-01-15 200 2021-01-31 300 2021-02-01 400 2021-02-15 500 2021-02-28 600 2021-03-01 700 2021-03-02 800 2021-03-03 900

要查找组的最新记录,您可以在上使用
DISTINCT:

SELECT DISTINCT ON (date_trunc('month', my_date))
    *
FROM mytable
ORDER BY date_trunc('month', my_date), my_date DESC
  • date\u trunc('month',…)
    将日期标准化为一个月的第一个月。因此,2月份内的每个日期都将转换为
    '2021-02-01'
    。这可以使用一组月
  • 按实际的
    日期描述对这些组进行排序,将最新日期排序到月份组的顶部
    DISTINCT ON
    准确返回此记录

  • 您可以使用row_number()执行此操作:


    查询#1

    select date,amount from 
    (
      select date,amount ,
      row_number()over (partition by (extract (year from date)),(extract (month from date )) order by date desc)RN
           from tablename
    )T
    WHERE RN=1;
    
    日期 数量 2021-01-31T00:00:00.000Z 300 2021-02-28:00:00.000Z 600 2021-03-04T00:00:00.000Z 1000
    很抱歉那是个打字错误。更正。由于同一个月在实际数据中可以存在多年,我将年和月一起用于按子句划分。添加了解释
    select date,amount from 
    (
      select date,amount ,
      row_number()over (partition by (extract (year from date)),(extract (month from date )) order by date desc)RN
           from tablename
    )T
    WHERE RN=1;
    
    select date_trunc('month', date + '01 Months'::interval) - '01 Days'::interval, sum(amount) 
    from tableName
    group by date_trunc('month', date + '01 Months'::interval) - '01 Days'::interval
    order by date_trunc('month', date + '01 Months'::interval) - '01 Days'::interval desc