2

我有一张桌子,上面有 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
4

3 回答 3

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
于 2009-06-03T11:24:35.067 回答
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
于 2009-06-03T23:12:48.847 回答
0

除了 Garry Shutler 的回答之外,更改位置的列和行可能会很有用,因为房间名称的数量肯定有限,但我们不能这样说日期。

于 2009-06-03T12:01:53.383 回答