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

时间:2013-10-10 07:06:09

标签: sql postgresql aggregate-functions greatest-n-per-group

这是我的表“AuctionDetails”

auction

以下选择:

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"

给了我这个结果:

here is my result

但我需要记录

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”,数量总和,以及拍卖编号的连接......

2 个答案:

答案 0 :(得分:1)

Postgres wiki描述了如何定义自己的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_(aggregate)

答案 1 :(得分: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

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