SQL GROUP BY和VALUE

时间:2011-09-05 09:53:02

标签: sql-server sql-server-2005

我有一张桌子

AvailbilityDate |   Resort    |  AccomName  |  Price    |  Min Occupancy
24 June 2012    |    Resort1  |    Accom1   |     999   |    8
24 June 2012    |    Resort1  |    Accom2   |     888   |    6
24 June 2012    |    Resort2  |    Accom1a  |     243   |    10
24 June 2012    |    Resort2  |    Accom2a  |     563   |    7

我目前拥有的是

SELECT AvailbilityDate, Resort, MIN(Price) AS Lowest 
FROM mytable 
GROUP BY AvailbilityDate, Resort

我希望能够获得AccomNameMin Occupancy

非常感谢提前

5 个答案:

答案 0 :(得分:1)

使用标准ANSI SQL,解决方案将是:

SELECT *
FROM (
   SELECT AvailbilityDate, 
          resort,
          accomName,
          price,
          min_occupancy,
          min(price) over (partition by AvailbilityDate, Resort) as min_price
   FROM deals_panel_view
) t
WHERE min_price = price;

应该适用于PostgreSQL,Oracle,DB2,SQL Server,Sybase和Terradata

答案 1 :(得分:1)

使用公用表表达式和排名函数可以执行此操作

WITH cte as (
SELECT 
  ROW_NUMBER() over (PARTITION BY AvailabilityDate,Resort ORDER BY price) as row,
  AvailbilityDate,
  Resort,
  AccomName,
  Price,
  [Min Occupancy] 
FROM mytable  
)
SELECT AvailbilityDate,Resort,Price,AccomName,[Min Occupancy] from cte where row=1

答案 2 :(得分:0)

SELECT AvailbilityDate, Resort, AccomName, "Min Occupancy", MIN(Price) AS Lowest 
FROM mytable 
GROUP BY AvailbilityDate, Resort

答案 3 :(得分:0)

您可以通过多种方式实现这一目标。

1)排名 - 根据a_horse_with_no_name的解决方案

2)分组和交叉申请。基本上插入要在第一个子查询中组合的列,然后所有其他列进入第二个子查询。在第二个子查询中使用Order By来处理要应用MIN(或MAX)的任何列。

SELECT a.AvailbilityDate, 
       a.resort,
       b.AccomName,
       b.min_occupancy,
       b.Lowest
FROM 
(
 SELECT t1.AvailbilityDate, t1.resort
  FROM myTable t1
  GROUP BY t1.AvailbilityDate, t1.resort
 ) a
CROSS APPLY
( 
  SELECT TOP 1 t2.AccomName, t2.min_occupancy, t2.price as Lowest
      FROM mytable t2
         WHERE t2.AvailbilityDate = a.AvailbilityDate
          AND t2.resort = a.resort
          ORDER BY t2.price ASC
) b

3)在分组语句中使用select语句中的子查询(不是非常优雅但有效)。这假设每个AvailbilityDate和度假村组合只有一个具有给定最低价格的住房。

SELECT a.AvailbilityDate, 
       a.resort,
       (SELECT accomName FROM myTable t1
         WHERE t1.AvailbilityDate = a.AvailbilityDate
          AND t1.resort = a.resort
          AND t1.price = MIN(a.price)
       ) as accomName,
       (SELECT min_occupancy FROM myTable t1
         WHERE t1.AvailbilityDate = a.AvailbilityDate
          AND t1.resort = a.resort
          AND t1.price = MIN(a.price)
       ) as min_occupancy,
       MIN(a.price) as Lowest
  FROM myTable a
  GROUP BY a.AvailbilityDate, a.resort

答案 4 :(得分:-1)

SELECT AccomName,MIN([Min Occupancy])AS from mytable GROUP BY AccomName

那只会给你想要的信息。如果你想在ADDITION中拥有你想要的所需字段,那就像是:

选择AvailbilityDate,AccomName,度假村,MIN(价格)AS最低,最低([最小入住率])作为最低要求来自mytable GROUP BY AvailbilityDate,AccomName,Resort