SQL简化了特征函数?或PIVOT表?

时间:2009-06-10 22:40:02

标签: mysql sql pivot aggregate-functions

我有一张桌子上有一堆日期和价格:

房间名称,价格,Bookdate等

我可以像这样改变它:(基本上翻转了列)

SELECT availables.name, rooms.id,
  MAX(IF(to_days(availables.bookdate) - to_days('2009-06-13') = 0, availables.price, '')) AS day1,
  MAX(IF(to_days(availables.bookdate) - to_days('2009-06-13') = 1, availables.price, '')) AS day2,
  MAX(IF(to_days(availables.bookdate) - to_days('2009-06-13') = 2, availables.price, '')) AS day3,
  MAX(IF(to_days(availables.bookdate) - to_days('2009-06-13') = 3, availables.price, '')) AS day4,
  MAX(IF(to_days(availables.bookdate) - to_days('2009-06-13') = 4, availables.price, '')) AS day5,
  MAX(IF(to_days(availables.bookdate) - to_days('2009-06-13') = 5, availables.price, '')) AS day6,
  MAX(IF(to_days(availables.bookdate) - to_days('2009-06-13') = 6, availables.price, '')) AS day7,
AVG(availables.price),SUM(availables.price)
FROM `availables`
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.room_id = '18382'
GROUP BY availables.name

这完美无缺,并产生了这个:

name    id  day1    day2    day3    day4    day5    day6    day7    AVG(availables.price)   SUM(availables.price)
Bed     18382   23.00   21.00   21.00   21.00   21.00   21.00       21.571429   151.00

但是我怎么能简化它因为我不知道天数?可能是1还是7?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

查看this answer及其链接的内容。