2010-07-07 54 views
2

我想寫一個高效的查詢,它返回一個水果類型列表,水果類型的最低價格和水果的名稱。現在,我有一個查詢返回給我的水果類型和該類型的最低價格(見下文)。但我無法得到最便宜的水果的名字。Group By和Aggregate函數

任何想法如何實現這一目標?謝謝。

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] 
+0

這是一門功課的問題嗎?如果是這樣,請標記爲這樣。也許這就是你如何說出你的問題,但你似乎有很多似乎是功課馬丁。 – 2010-07-07 18:21:22

回答

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 
+0

謝謝!我將使用排名解決方案! – Martin 2010-07-07 18:27:51

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) 

請記住,如果您的某個類別中有多個項目,並且價格相同,您將獲得多個結果。

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 
    )