SQL select TOP 记录按多列中的几列分区
SQL select TOP records partition by couples of column from multiple columns
我要的是所有customer
总成本TOP2,所有属性都需要的。),
问题是SQL使用起来太复杂了,有没有办法简化一下?
日期 table
和我的 SQL
如下所示:
area
customer
property
cost
area1
cus1
property11
cost11
area1
cus1
property12
cost12
area1
cus2
property21
cost21
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
)a
WHERE number <=2
)aa
)aaa
GROUP BY
area,
customer,
property
您可以使用 ROW_NUMBER()
window 函数(或者 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
我要的是所有customer
总成本TOP2,所有属性都需要的。),
问题是SQL使用起来太复杂了,有没有办法简化一下?
日期 table
和我的 SQL
如下所示:
area | customer | property | cost |
---|---|---|---|
area1 | cus1 | property11 | cost11 |
area1 | cus1 | property12 | cost12 |
area1 | cus2 | property21 | cost21 |
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
)a
WHERE number <=2
)aa
)aaa
GROUP BY
area,
customer,
property
您可以使用 ROW_NUMBER()
window 函数(或者 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