Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择max(id)具有max(付款日期)的行_Sql_Postgresql - Fatal编程技术网

Sql 选择max(id)具有max(付款日期)的行

Sql 选择max(id)具有max(付款日期)的行,sql,postgresql,Sql,Postgresql,我一直在尝试获取每个帐户id的max(付款日期)的max(id),因为在某些情况下,同一max(付款日期)有不同的条目。ID是帐户ID的付款参考。因此,每个帐户id都需要有一个带有该日期的max(付款日期)和max(id)的条目。问题是,有些条目中帐户id的最大值(id)不是最大值(付款日期),否则我只会使用最大值(id)。由于此原因,下面的代码不起作用,因为它将排除max(id)不是max(付款日期)的条目。提前谢谢 select * from ( select payments.*

我一直在尝试获取每个帐户id的max(付款日期)的max(id),因为在某些情况下,同一max(付款日期)有不同的条目。ID是帐户ID的付款参考。因此,每个帐户id都需要有一个带有该日期的max(付款日期)和max(id)的条目。问题是,有些条目中帐户id的最大值(id)不是最大值(付款日期),否则我只会使用最大值(id)。由于此原因,下面的代码不起作用,因为它将排除max(id)不是max(付款日期)的条目。提前谢谢

select *
from (
  select payments.* 
  from (
    select account_id, max(payment_date) as last_payment, max(id) as last_payment1 
    from energy.payments 
    where state = 'success' 
      and amount_pennies > 0 
      and description not ilike '%credit%' 
      group by account_id 
  ) as last_payment_table
  inner join energy.payments as payments 
         on payments.account_id = last_payment_table.account_id
        and payments.payment_date = last_payment_table.last_payment
        and payments.id = last_payment_table.last_payment1
) as paymentst1

在上使用
不同。我无法真正理解您的查询(示例数据非常有用!),但我的想法是:

select distinct on (p.account_id) p.*
from energy.payments p
order by p.account_id, p.payment_date desc, p.id desc;

您可以添加额外的逻辑进行过滤或其他操作。您的问题中没有解释这种逻辑,但您所包含的代码建议了这种逻辑。

很难理解这个问题,但我认为您的意思是:



或者,使用窗口功能:


SELECT *
FROM payments  p
WHERE NOT EXISTS (
        SELECT *
        FROM payments  nx
        WHERE nx.account_id = p.account_id      -- same account
        AND nx.payment_date >= p.payment_date   -- same or more recent date
        AND nx.id > p.id                        -- higher ID
        );
select *
from (
  select * 
    , row_number() OVER(PARTITION BY account_id
                        ORDER BY payment_date DESC,id DESC) as rn
    from energy.payments
    where state = 'success' 
      and amount_pennies > 0 
      and description not ilike '%credit%' 
) x
WHERE x.rn=1
        ;