最大行分组

时间:2019-04-11 19:05:35

标签: sql postgresql group-by

我尝试通读我找到的许多解决方案,但是在不确定不确定如何使它们适应我自己的问题上似乎有些细微的差异。

我有一张类似的交易表:

+------+-------+------------------------------+
| id   | rev_$ | product  | local_currency    |
+------+-------+------------------------------+
| 1    | 15    | shoe     | USD               |
| 2    | 10    | shirt    | USD               |
| 1    | 20    | shoe     | CAD               |
| 2    | 30    | shoe     | GBP               |
| 1    |  8    | shirt    | USD               |
| 2    | 15    | shirt    | USD               |
| 1    | 10    | shoe     | CAD               |
| 2    | 10    | shoe     | USD               |
+------+-------+------------------------------+

我想汇总表,以便

  • 我按产品获得每个ID的总数
  • local_currency是用于最高单价值交易的货币(以及我未包括的其他字段)

因此,汇总后该表应如下所示:

+------+-------+------------------------------+
| id   | rev_$ | product  | local_currency    |
+------+-------+------------------------------+
| 1    | 45    | shoe     | CAD               |
| 1    |  8    | shirt    | USD               |
| 2    | 25    | shirt    | USD               |
| 2    | 40    | shoe     | GBP               |
+------+-------+------------------------------+

相似的问题:(1)(2)

2 个答案:

答案 0 :(得分:4)

您可以使用group by计算总收入,收集数组中的所有货币,然后从最高值中选择一种:

select id, 
       sum(rev_$), 
       product, 
       (array_agg(local_currency order by rev_$ desc))[1] as local_currency
from orders
group by id, product
order by id, product;

array_agg(local_currency order by rev_$ desc)将为group by降序排列的rev$定义的组中的所有货币创建一个数组。因此,第一个元素([1]是与“最高单一价值交易”相对应的一个元素

在线示例:https://rextester.com/VOK41538


另一种选择是编写一个aggregate function而不使用数组:

create or replace function first_agg (p_one anyelement, p_other anyelement )
  returns anyelement 
  language sql 
  immutable strict
as
$$
  select p_one;
$$;

create aggregate first_element 
(
  sfunc    = first_agg,
  basetype = anyelement,
  stype    = anyelement
);

然后您可以像这样使用它:

select id, 
       sum(rev_$), 
       product, 
       first_element(local_currency order by rev_$ desc) as local_currency
from orders
group by id, product
order by id, product;

在线示例:https://rextester.com/YGRR9338

答案 1 :(得分:1)

可以使用一些子查询

select  m2.id, sum(m2.rev_$), t2.local_currency
my_table m2
from  (
  select distinct local_currency, id  
  from my_table m1 
  inner join  (
    select  id, max(rev_$) max_rev
    from  my_table 
    group by id 
  ) t1  on t1.id = m1.id and t1.max_rev = m1.rev_$ 
) t2 ON m2.id= t2.id