sql从多个列中选择按列对划分的顶级记录

z9ju0rcb  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(359)

例如,我需要选择每个区域的前2位客户(不包括 property ),每个客户都有不同的属性,如

面积|客户|财产|成本

区域1 | cus1 |物业11 |成本11
区域1 | cus1 |物业12 |成本12
区域1 | cus2 |物业21 |成本21
通常下面的sql语句是可以的,但是这次 table 是一个复杂的嵌套sql语句,所以我想知道是否有更好的方法来简化它(如果cus1在top2中,则需要所有属性)
thx的任何建议或解决问题的链接。

SELECT
    area,
    customer,
    property,
    SUM(cost) AS cost
FROM
    table
WHERE
    customer IN
             (SELECT
                  f.customer
             FROM
                 (SELECT
                      p.area,
                      p.customer,
                      ROW_NUMBER() OVER(PARTITION BY area ORDER BY cost) AS number,
                      p.cost
                 FROM(SELECT
                          area,
                          costomer,
                          SUM(cost) AS cost
                     FROM
                         table
                     GROUP BY
                         costomer
                     )p
             WHERE number <=2)A
            )
GROUP BY
    area,
    customer,
    property
jucafojl

jucafojl1#

你可以用 ROW_NUMBER() 窗口功能(或 RANK() 如果您想包括领带):

select t.area, t.customer, t.properties, t.cost
from (
  select area, customer, collect_set(property) properties, sum(cost) cost, 
    row_number() over (partition by area order by sum(cost) desc) rn
  from tablename
  group by area, customer
) t
where t.rn <= 2

相关问题