使用SQL进行压缩查询

时间:2009-06-03 11:19:05

标签: sql mysql group-by aggregate sql-order-by

我有一张桌子,里面有我想要的4件事......名称,价格,数量和特定的日期

每个日期有很多条目:

Name          Price  Date

Twin Private  $25    06/02/09
Double        $35    06/02/09
Single        $20    06/02/09
Twin Private  $25    06/03/09
Double        $35    06/03/09
Single        $20    06/03/09
Twin Private  $25    06/04/09
Double        $35    06/04/09
Single        $20    06/04/09

我如何将其压缩成:

Name          Price_06/02/09  Price_06/03/09  Price_06/04/09

Twin Private  $25             $25             $30
Double        $35             $35             $50
Single        $20             $20             $40

3 个答案:

答案 0 :(得分:7)

我认为这样做会:

select  Name,
        max(Price_06/02/09) as Price_06/02/09,
        max(Price_06/03/09) as Price_06/03/09,
        max(Price_06/04/09) as Price_06/04/09
from    (
        select    Name,
                  case Date
                      when '06/02/09' then Price
                      else null
                  end as Price_06/02/09,
                  case Date
                      when '06/03/09' then Price
                      else null
                  end as Price_06/03/09,
                  case Date
                      when '06/04/09' then Price
                      else null
                  end as Price_06/04/09
        from      Rates) as Aggregated
group by 
        Name

这有两个阶段,内部查询将数据拉伸出来,所以你最终得到:

Name          Price_06/02/09  Price_06/03/09  Price_06/04/09

Twin Private  $25             null            null
Double        $35             null            null
Single        $20             null            null
Twin Private  null            $25             null
Double        null            $35             null
Single        null            $20             null
Twin Private  null            null            $25
Double        null            null            $35
Single        null            null            $20

然后外部查询按名称分组以将其展平为:

Name          Price_06/02/09  Price_06/03/09  Price_06/04/09

Twin Private  $25             $25             $25
Double        $35             $35             $35
Single        $20             $20             $20

答案 1 :(得分:1)

我最终使用了这样的东西:

我正在使用mysql,它是否支持PIVOT?

SELECT


    name, room_id,

      MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 0, price, '')) AS Day1,
      MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 1, price, '')) AS Day2,
      MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 2, price, '')) AS Day3,
      MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 3, price, '')) AS Day4,
      MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 4, price, '')) AS Day5,
      MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 5, price, '')) AS Day6,
      MAX(IF(to_days(bookdate) - to_days('2009-06-24') = 6, price, '')) AS Day7, spots
    FROM `availables`
    GROUP BY name

答案 2 :(得分:0)

除了Garry Shutler answer之外,更改地点中的列和行可能很有用,因为肯定只有有限数量的房间名称,但我们无法说明日期。