sql—检索每个组中的三个最高值

q3aa0525  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(472)

有一个名为“purchase\u history”的表,其中包含如下所示的数据:

ID          product           price
123           abcd          1000
123           aaaa          2000
123           aaaa          3000
456           yyyy          50
456           bbbb          6000
456           cccc          450

我想提取产品名称和金额最高的3个价格为每个用户。我希望每个用户(即使购买少于3次)都有一个输出行,字段为user\u id、product\u name\u 1、amount\u 1、product\u name\u 2、amount\u 2、product\u name\u 3、amount\u 3
有什么办法能达到这个效果吗?

yeotifhr

yeotifhr1#

使用 ROW_NUMBER() 窗口函数筛选每个用户的前3个价格,然后使用条件聚合:

select t.id,
  max(case when t.rn = 1 then product end) product_name_1, 
  max(case when t.rn = 1 then price end) amount_1,
  max(case when t.rn = 2 then product end) product_name_2, 
  max(case when t.rn = 2 then price end) amount_2,
  max(case when t.rn = 3 then product end) product_name_3, 
  max(case when t.rn = 3 then price end) amount_3
from (
  select *, row_number() over (partition by id order by price desc) rn 
  from tablename
) t
where t.rn <= 3
group by t.id

请看演示。
结果:

| id  | product_name_1 | amount_1 | product_name_2 | amount_2 | product_name_3 | amount_3 |
| --- | -------------- | -------- | -------------- | -------- | -------------- | -------- |
| 123 | aaaa           | 3000     | aaaa           | 2000     | abcd           | 1000     |
| 456 | bbbb           | 6000     | cccc           | 450      | yyyy           | 50       |
wpcxdonn

wpcxdonn2#

使用行号()

select a.* from     
(select *, row_number() over(partition by id order by price desc) rn
from table_name
) a where a.rn=1

select a1.* from table_name a1
  where a1.price=( select max(price) from table_name a2
                 where a1.id=a2.id)

或在后灰色中清晰可见

SELECT DISTINCT ON (id) id, product,price
FROM table_name
ORDER BY id,price DESC

相关问题