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

标签 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”,数量总和,以及拍卖编号的串联......

最佳答案

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)

关于sql - 在 PostgreSQL 中使用 group by 时如何获取最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19289189/

相关文章:

sql - 如何根据不同行的左外连接关系的属性生成函数值

postgresql - 如何在 group by 子句后应用 case when 语句

sql - 逐行求和并选择结果集中的其他列

jquery - 使用 google 可视化 api 查询多个表

c# - 拆分/合并具有 'nested' 外键引用的 shardlet

ruby - 什么是更聪明的选择 : Ruby logic or SQL function?

sql - 左连接充当内部连接?

php - 显示来自 MySQL 数据库的唯一值

postgresql - Postgres 函数更新列不明确

node.js - NestJS : Case-insensitive search in PostgreSQL