【问题标题】:Group By and Aggregate function分组依据和聚合函数
【发布时间】:2010-07-07 18:16:08
【问题描述】:

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

知道如何实现吗?谢谢。

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]

【问题讨论】:

  • 这是一道作业题吗?如果是这样,请将其标记为这样。也许这是你表达问题的方式,但你似乎有很多看起来像家庭作业马丁。

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


【解决方案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

【讨论】:

  • 谢谢!我将使用排名解决方案!
【解决方案2】:

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

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)

请记住,如果您在一个类别中有多个相同价格的商品,至少您会得到多个结果。

【讨论】:

    【解决方案3】:

    如果您的表具有代理主键,您可以使用一个简单的技巧进行此类查询。 (其实不用一个也可以,但是比较复杂。)

    设置:

    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
       )
    

    【讨论】:

      猜你喜欢
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2020-01-17
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多