如何在PostgreSQL中使用group by时获取最后一条记录

3

这是我的表格"AuctionDetails"

拍卖

下面是查询语句:

select string_agg("AuctionNO",',' ) as  "AuctionNO"
      ,sum("QuntityInAuction" ) as "QuntityInAuction"
      ,"AmmanatPattiID"
      ,"EntryPassDetailsId" 
      ,"BrokerID"
      ,"TraderID"
      ,"IsSold"
      ,"IsActive"
      ,"IsExit"
      ,"IsNew"
      ,"CreationDate"
from "AuctionDetails"
group by "AmmanatPattiID"
        ,"EntryPassDetailsId"  
        ,"TraderID"
        ,"IsSold"
        ,"IsActive"
        ,"IsExit"
        ,"IsNew"
        ,"BrokerID"
        ,"CreationDate"

这是我的结果:

这是我的结果

但我需要像这样的记录:

AuctionNo                                QunatityInAuction  AmmanatpattiID  EntryPassDetailID  BrokerID  Trader ID  IsSold  ISActive  ISExit  IsNew  CreationDate
AU8797897,AU8797886,AU596220196F37379    1050               -1               228,229            42         42         f         t       f      t      2013-10-10

最后,我需要一个交易员和经纪人的最新条目,这在我们的情况下是“42”,数量总和和拍卖号的连接。


“Latest” 是由 CreationDate 定义的吗?仍然缺少 pk 定义和 Postgres 版本(运行 SELECT version())。这两个对查询都很重要。 - Erwin Brandstetter
"AuctionID" 是我的主键。 - Aijaz Chauhan
版本是“PostgreSQL 9.0.12,由Visual C++ build 1500编译,32位”。 - Aijaz Chauhan
最新的记录可以通过主键进行识别...在我们的情况下,最新的记录是拍卖ID为137的第3条记录。 - Aijaz Chauhan
2个回答

2
Postgres维基描述了如何定义您自己的FIRST和LAST聚合函数。例如:
-- Create a function that always returns the last non-NULL item
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$
        SELECT $2;
$$;

-- And then wrap an aggregate around it
CREATE AGGREGATE public.LAST (
        sfunc    = public.last_agg,
        basetype = anyelement,
        stype    = anyelement
);

页面在这里:https://wiki.postgresql.org/wiki/First/last_(聚合)


0

有多种方法可以实现这一点。可以使用聚合和窗口函数的组合,或者使用窗口函数和 DISTINCT 的组合...

SELECT a.*, b.*
FROM  (
   SELECT string_agg("AuctionNO", ',') AS  "AuctionNO"
         ,sum("QuntityInAuction") AS "QuntityInAuction"
   FROM   "AuctionDetails"
   ) a
CROSS JOIN (
   SELECT "AmmanatPattiID"
         ,"EntryPassDetailsId" 
         ,"BrokerID"
         ,"TraderID"
         ,"IsSold"
         ,"IsActive"
         ,"IsExit"
         ,"IsNew"
         ,"CreationDate"
   FROM   "AuctionDetails"
   ORDER  BY "AuctionID" DESC
   LIMIT  1
   ) b

对于整个表只有一行结果的简单情况,这可能是最简单的方法。


这不是一个正确的解决方案......我需要经纪人和交易员的最后一条记录,而在我们的情况下是第二条记录。 - Aijaz Chauhan
@AijazChauhan:根据什么排序规则来确定“Last”?请编辑您的问题并提供一个合适的定义。还需提供一个包括主键的表定义和您使用的Postgres版本。 - Erwin Brandstetter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接