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

问题描述 投票:2回答:2

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

sql postgresql aggregate-functions greatest-n-per-group
2个回答
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

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


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)

© www.soinside.com 2019 - 2024. All rights reserved.