我有一张这样的 table
attribute_id product_id quantity
1 101 10
2 101 7
3 101 8
4 102 2
5 102 8
6 102 6
7 103 30
8 103 25
9 103 20
查询完之后,我想找一个这样的查询。 这是半答案
attribute_id product_id quantity
3 101 8
6 102 6
9 103 20
最终输出将是
最佳答案
您可以使用 top 1 with ties
和 row_number
来获取具有最大 attribute_id 的每个 product_id 的行,并对找到的数量使用 sum
值(value)观。
select sum(quantity) as quantity
from (
select top 1
with ties quantity
from your_table
order by row_number() over (
partition by product_id order by attribute_id desc
)
) t;
Demo
关于mysql - 如何在sql查询中添加同一组的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44275390/