选择包含和不包含分组的列

时间:2014-06-20 11:29:45

标签: sql

拥有Table1

id | productname | store   | price  
-----------------------------------  
1  |      name a | store 1 |     4  
2  |      name a | store 2 |     3  
3  |      name b | store 3 |     6  
4  |      name a | store 3 |     4  
5  |      name b | store 1 |     7  
6  |      name a | store 4 |     5  
7  |      name c | store 3 |     2  
8  |      name b | store 6 |     5  
9  |      name c | store 2 |     1  

我需要获取所有列,但只能获取带有的行 最低价格 需要的结果:

id | productname | store   | price  
-----------------------------------  
2  |      name a | store 2 |     3  
8  |      name b | store 6 |     5  
9  |      name c | store 2 |     1  

我最好的尝试是:

SELECT ProductName, MIN(Price) AS minPrice  
FROM Table1  
GROUP BY ProductName  

但是我需要每行IDSTORE

5 个答案:

答案 0 :(得分:1)

试试这个

select p.* from  Table1 as p inner join 
(SELECT ProductName, MIN(Price) AS minPrice    FROM Table1      GROUP BY ProductName) t 
on p.productname  = t.ProductName and p.price = t.minPrice    

答案 1 :(得分:1)

Select ID,ProductName,minPrice
from
(
SELECT ProductName, MIN(Price) AS minPrice
FROM Table1
GROUP BY ProductName
) t
join Table1 t1 on t.ProductName = t1.ProductName

答案 2 :(得分:1)

您没有提及您的SQL方言,但大多数DBMS支持标准SQL的“窗口聚合函数”:

select *
from
  ( select t.*,
       RANK() OVER (PARTITION BY ProductName ORDER BY Price) as rnk 
    from table1 as t
  ) as dt
where rnk = 1

如果多家商店的价格相同,则会退回所有商店。如果您只想要一个商店,则必须切换到ROW_NUMBER而不是RANK或将列添加到ORDER BY。

答案 3 :(得分:0)

这应该适合你:

SELECT * FROM `Table1` AS `t1`
WHERE (
   SELECT count(*) FROM `Table1` AS `t2` WHERE `t1`.`productName` = `t2`.`productName` AND `t2`.`price` < `t1`.`price`) < 1

检查SqlFiddle

但如果您在两个商店中拥有相同的最低价格的产品,您将获得两个结果输出

答案 4 :(得分:0)

我认为这个查询应该这样做:

select min(t.id) id
,      t.productname
,      t.price
from   table1 t
join
( select min(price) min_price
  ,      productname
  from   table1
  group
  by     productname
) v
on     v.productname = t.productname
and    v.price = t.min_price
group
by     t.productname
,      t.price

它确定每个产品的最低价格并获取基表(t)中的每一行。这可以通过对productname进行分组并选择最低id来避免重复。