Group By和Aggregate功能

时间:2010-07-07 18:16:08

标签: sql sql-server group-by aggregate-functions

我想写一个有效的查询,它按类型返回水果列表,水果类型的最低价格和水果的名称。现在,我有一个查询,它返回水果类型和该类型的最低价格(见下文)。但是我无法得到最便宜的水果的名字。

知道如何实现这一目标吗?感谢。

CREATE TABLE Fruits (
    [type] nvarchar(250),
    [variety] nvarchar(250),
    [price] money
)
GO

INSERT INTO Fruits VALUES ('Apple', 'Gala', 2.79)
INSERT INTO Fruits VALUES ('Apple', 'Fuji', 0.24)
INSERT INTO Fruits VALUES ('Apple', 'Limbertwig', 2.87)
INSERT INTO Fruits VALUES ('Orange', 'Valencia', 3.59)
INSERT INTO Fruits VALUES ('Pear', 'Bradford', 6.05)

SELECT type, MIN(price)
FROM   Fruits
GROUP BY [type]

3 个答案:

答案 0 :(得分:1)

使用:

SELECT f.*
  FROM FRUITS f
  JOIN (SELECT t.type,
               MIN(t.price) AS min_price
          FROM FRUITS t
      GROUP BY t.type) x ON x.type = f.type
                        AND x.min_price = f.price

我认为你正在使用SQL Server - 如果是v2005或更新版本,你也可以使用分析/排名/窗口功能:

SELECT f.type, f.variety, f.price
  FROM (SELECT t.type, t.variety, t.price,
               ROW_NUMBER() OVER (PARTITION BY t.type ORDER BY t.price) AS rank
          FROM FRUITS t) f
 WHERE f.rank = 1

答案 1 :(得分:1)

有很多方法可以做到这一点,下面有一个解决方案。

SELECT F2.type, f2.variety, f2.price
FROM 
(
    SELECT type, min(price) as price
    FROM Fruits
    GROUP BY [type]
) as MinData
    INNER JOIN Fruits F2
        ON (MinData.type = Type = F2.Type
            AND MinData.price = F2.Price)

请注意,如果某个类别中的多个商品至少具有相同的价格,您将获得多个结果。

答案 2 :(得分:0)

如果您的表具有代理主键,则可以使用这种查询的简单技巧。 (实际上,你可以在没有一个的情况下做到这一点,但它更复杂。)

设置:

if object_id('tempdb..#Fruits') is not null drop table #Fruits
create table #Fruits (
  [id] int identity(1,1) not null,
  [type] nvarchar(250),
  [variety] nvarchar(250),
  [price] money
)

insert into #Fruits ([type], [variety], [price])
select 'Apple', 'Gala', 2.79 union all
select 'Apple', 'Fuji', 0.24 union all
select 'Apple', 'Limbertwig', 2.87 union all
select 'Orange', 'Valencia', 3.59 union all
select 'Pear', 'Bradford', 6.05

现在是SQL:

select * -- no stars in PROD!
from #Fruits a
where
   a.id in (
      select top 1 x.id
      from #Fruits x
      where x.[type] = a.[type]
      order by x.price
   )