将不在汇总函数中的列保留在group by语句中

时间:2018-10-03 07:17:22

标签: sql oracle group-by aggregate-functions greatest-n-per-group

我想修改一个现有的选择,使其输出具有每个客户的MAX(amount)及其所有值的行。 目前的结果是这样的。

   AMOUNT CUSTOMERID     ITEMID USERNAME                        USERID SUMMARYDAY

    60    198507        205 luk                                   12 03.10.18
   300    198526        207 max                                   12 03.10.18
 20000    198507        126 luk                                   12 03.10.18
  6000    198526        158 max                                   12 03.10.18
  1200    198526        206 max                                   12 03.10.18

但是我想要这个:

   AMOUNT CUSTOMERID     ITEMID USERNAME                        USERID SUMMARYDAY

  20000    198507        126 luk                                   12 03.10.18
  6000     198526        158 max                                   12 03.10.18

当前查询:

SELECT max(totalamount) as amount, cg.customerId, g.itemid,
       (select c.nickname from customer c where c.customerId=cg.customerid) as nickname,
       12 as clientId, sysdate as summaryDate
FROM ItemBuy cg,
     ItemToSell gf,
     Item g
WHERE cg.itemSellId = gf.itemSellId and gf.itemId = g.itemId
  and cg.type = 0 and cg.shopId = 12
  and cg.starttime >= sysdate-100 and cg.starttime < sysdate+100
group by cg.customerId
having max(totalamount) > 0

我稍微匿名了一下查询,但是我的主要问题是:

我该如何在group by语句中保留特定列,并告诉sql在g​​roup by和max()都“选择”一行之后才保留它。

非常感谢您!

1 个答案:

答案 0 :(得分:2)

我建议采用这种简单的方法,并将您的描述“ 将每位客户的MAX(金额)及其所有值输出到该行”到SQL:

select * from a_table t
where (t.customerid,t.amount) in (
   select customerid,max(amount) from a_table group by customerid);

让我知道是否需要更多输入。