显示带有maxgroupby和两列sql的行



已经提出了许多不同的问题,但似乎找不到适合我的表的问题。我有三个专栏pd、stm和salesgrease。我想找出每个stm的销售额增长的最大值。

  pd        stm    salesincrease
Chamomile   Central 801
Caffe Mocha Central 752
Earl Grey   Central 725
Colombian   East    975
Lemon       East    573
RegEspresso East    531
Caffe Mocha East    356
Lemon       West    667
DeEspresso  West    664
Colombian   West    628
Darjeeling  West    623

我遇到的问题是:

select  stm, pd, max(salesincrease) as maxsales from
table
group by stm, pd;

它没有显示出正确的结果。我也试过:

select  stm, max(salesincrease) as maxsales from
table
group by stm;

这显然显示了stm和max,但我无法在没有错误的情况下获得产品名称

理想情况下,我想要这样的输出:

  pd        stm    salesincrease
Chamomile   Central 801
Colombian   East    975
Lemon       West    667

使用row_number():

select pd, stm, salesincrease
from (select t.*, row_number() over (partition by stm order by salesincrease desc) as seqnum
      from table t
     ) t
where seqnum = 1;

以下查询应该返回您要查找的结果:

WITH maxsalesincrease AS
(
SELECT stm, max(salesincrease) AS maxsales
FROM table
GROUP BY stm
)
SELECT t.pd, t.stm, t.sales
FROM table t, maxsalesincrease s
WHERE t.salesincrease = s.maxsales
    AND t.stm = s.stm

这创建了一个CTE,它为我们提供了该stm的最大销售额增长。然后我们将其加入到原始表中,其中salesrangement等于maxsales,stms匹配。如果同一stm中的两个pd具有相同的最大值(销售额增加),这也将正确返回结果。

相关内容

  • 没有找到相关文章

最新更新