有一个guaccountid有3个不同的guorderid值和不同的enddate。我只需要得到特定enddate的最新guorderid

select guaccountid,guorderid,enddate
from ord_entitlement
where guaccountid ='15031021282118408'
ORDER BY enddate DESC

postgresql - 如何在PostgreSQL中获取最新日期?-LMLPHP

最佳答案

我将使用row_number()窗口函数:

SELECT
  guaccountid,
  guorderid,
  enddate
FROM (
  SELECT
    guaccountid,
    guorderid,
    enddate,
    row_number() over (
      partition by guaccountid
      order by to_timestamp(enddate, 'YYYY-MM-DD"T"HH24:MI:SS') desc
    ) r
  FROM ord_entitlement
  WHERE guaccountid = '15031021282118408'
    AND substr(enddate, 1, 4) != '9999'
  ) src
WHERE r = 1;

这将返回:
|       guaccountid |         guorderid |            enddate |
|-------------------|-------------------|--------------------|
| 15031021282118408 | 15031708485830901 | 2015-04-16T08:42:1 |

如果从guaccountid = '15031021282118408'子句中删除where,您将获得任何guaccountid的最新记录。
Sample SQL Fiddle

关于postgresql - 如何在PostgreSQL中获取最新日期?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31854134/

10-15 16:36