mysql - 如何在sql查询中添加同一组的最后一个值

标签 mysql sql sql-server database

我有一张这样的 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

最终输出将是

this

最佳答案

您可以使用 top 1 with tiesrow_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/

相关文章:

SQL - 如何根据另一个属性限制一个属性的数据输入?

MySQL LEFT OUTER JOIN 选择最佳匹配而不更改 sql_mode

mysql - 在 Firebase 中发送通知之前 Node Js 查询 MySql

mysql - 允许任何 MAC 管理员用户在启动时运行 MySQL 服务器

sql - 分区上窗口函数中的 PostgreSQL 错误?

sql-server - 动态查询结果进入临时表或表变量

sql - 计算考勤时差

mysql - Grafana世界地图面板: latitude and longitude in mysql cannot display points on map

sql - 使用 SQL 在查询中引用表单上的字段

php - MySQL Join 将不匹配的记录包含在 WHERE 语句中