SQL和Group By查询

时间:2016-05-24 11:43:27

标签: mysql sql sql-server

我有桌面材料:

 - id: int
 - Product: varchar (100)
 - Content: text 
 - price: double

我想显示具有最终价格的产品组的材料列表 我尝试过:

 SELECT  * FROM materiel GROUP BY produit ORDER BY id

但在我看来,这是一个按产品分列的第一个奖项

13, product1, dell, 25
14, product2, hp, 4 
17, product3, acer, 15 

不使用group by

的查询
13, product1, dell, 25
14, product2, hp, 4 
16, product1, acer, 35
17, product3, acer, 15 

我想要这个节目

14, product2, hp, 4
16, product1, acer, 35 
17, product3, acer, 15 

3 个答案:

答案 0 :(得分:1)

您可以使用IN()声明:

SELECT * FROM product p
WHERE p.product,p.id IN(SELECT p1.product,max(p1.id)
                        FROM product p1
                        GROUP BY p1.product)

JOIN

SELECT p.* FROM product p
INNER JOIN (SELECT p1.product,max(p1.id) as max_id
            FROM product p1
            GROUP BY p1.product) p1
 ON(p.id = p1.max_id and p.product = p1.product)

答案 1 :(得分:1)

一种方法使用相关子查询:

select m.*
from material m
where m.id = (select max(m2.id) from material m2 where m2.product = m.product);

我更喜欢这种方法,因为子查询可以利用material(product, id)上的索引,因此它可以比聚合方法更快。此外,如果您有其他条件(比如price > 100),那么这应该更快。

或者,在SQL Server中,典型方式使用row_number()

select m.*
from (select m.*,
             row_number() over (partition by product order by id desc) as seqnum
      from material m
     ) m
where seqnum = 1;

答案 2 :(得分:0)

SELECT  m.* 
FROM materiel m
LEFT JOIN materiel m1
ON m.produit  = m1.produit 
  AND m.id<m1.id
WHERE m1.id IS NULL