有一个名为“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
有什么办法能达到这个效果吗?
2条答案
按热度按时间yeotifhr1#
使用
ROW_NUMBER()
窗口函数筛选每个用户的前3个价格,然后使用条件聚合:请看演示。
结果:
wpcxdonn2#
使用行号()
或
或在后灰色中清晰可见