Group By Clause中的聚合函数

时间:2016-11-16 18:59:50

标签: sql postgresql

我通过查询使用以下组来删除冗余事务(de dupe):

SELECT
    optimized_transaction_date,
    cobrand_id,
    merchant_name,
    Description,
    UNIQUE_MEM_ID,
    Amount,
    distinct_count as members,

    into   xx
    FROM yy
    WHERE xx)



GROUP BY optimized_transaction_date ,
        cobrand_id ,
        merchant_name,
        Description ,
        UNIQUE_MEM_ID ,
        Amount,
        members

但是我添加了一些我想申请的聚合函数:

SELECT
    optimized_transaction_date,
    cobrand_id,
    merchant_name,
    Description,
    UNIQUE_MEM_ID,
    Amount,
    distinct_count as members,
    Amount/members as calc,
    cast(count(amount) as DOUBLE PRECISION)/members as count


    into   xx
    FROM yy
    WHERE xx)


    GROUP BY optimized_transaction_date ,
            cobrand_id ,
            merchant_name,
            Description ,
            UNIQUE_MEM_ID ,
            Amount, 
            members
            calc

问题是计算,尤其是计数现在返回包含冗余事务的总和/计数。例如,当存在重复事务时,count字段将返回值x2其他行。如何编写我的查询,以便它只返回计数组的计算结果(重复交易)。

由于

1 个答案:

答案 0 :(得分:0)

通常不可能在(https://www.postgresql.org/message-id/7608.1259177709%40sss.pgh.pa.us)组中使用别名 所以你可以重复原始值

SELECT
    optimized_transaction_date,
    cobrand_id,
    merchant_name,
    Description,
    UNIQUE_MEM_ID,
    Amount,
    distinct_count as members,
    Amount/members as calc,
    cast(count(amount) as DOUBLE PRECISION)/members as count


    into   xx
    FROM yy
    WHERE xx)


    GROUP BY optimized_transaction_date ,
            cobrand_id ,
            merchant_name,
            Description ,
            UNIQUE_MEM_ID ,
            Amount, 
            distinct_count
            (Amount/distinct_count)