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

时间:2017-05-31 03:59:53

标签: mysql sql sql-server database

我有一张这样的表

  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

6 个答案:

答案 0 :(得分:2)

您可以将top 1 with tiesrow_number一起使用,以获取具有max attribute_id的每个product_id的行,并对找到的数量值使用sum

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

答案 1 :(得分:0)

试试这个

Select sum(quantity) as quantity 
  from table 
where attribute_id in 
   (Select max(attribute_id) from 
     table 
     Group by product_id
   ) t

内部查询将为您提供属性ID 3,6,9,您可以在外部查询中对其数量求和。

答案 2 :(得分:0)

尝试使用:使用子查询,并为每个attribute_idMAX product_id,并按以下方式加入:

select sum(quantity) from <table> t
inner join (select product_id, 
                max(attribute_id) as attribute_id 
            from <table> 
            group by product_id) t1 on t1.product_id = t.product_id
    and t1.attribute_id = t.attribute_id

答案 3 :(得分:0)

SELECT
SUM(tnm.quantity) AS MaxQuantity
FROM(
select product_id , MAX(attribute_id) AS LastAttribute
from table_Name1
group by product_id
)lc inner join table_Name1 as tnm on tnm.attribute_id =  lc.LastAttribute 
AND tnm.product_id =  lc.product_id

答案 4 :(得分:0)

试试这个......

select sum(b.quantity)
from   table_Name1 
where  Attribute_id in 
       (Select max(Attribute_id)
        from  table_Name1 group by Product_Id)

答案 5 :(得分:0)

;With cte(attribute_id,product_id,quantity)
AS
(
SELECT  1,101,10 UNION ALL
SELECT  2,101,7  UNION ALL
SELECT  3,101,8  UNION ALL
SELECT  4,102,2  UNION ALL
SELECT  5,102,8  UNION ALL
SELECT  6,102,6  UNION ALL
SELECT  7,103,30 UNION ALL
SELECT  8,103,25 UNION ALL
SELECT  9,103,20
)
SELECT SUM(quantity) As Sumquantity From
(
SELECT *,Row_number()OVER(Partition BY product_id order by attribute_id) AS Rno from cte
)dt where dt.Rno=3