如何在mysql中使用n行旋转表?

时间:2015-04-08 03:33:37

标签: mysql pivot-table

如果我有1000行,我想成为每一行到列,行可以是任何行 我是怎么用mysql做的?

1 个答案:

答案 0 :(得分:0)

以下是工作日按房间预订的MySQL数据透视表查询:

SELECT slot 
  , max(if(day=1, concat(subject,' ',room), '')) as day1 
  , max(if(day=2, concat(subject,' ',room), '')) as day2 
  , max(if(day=3, concat(subject,' ',room), '')) as day3 
  , max(if(day=4, concat(subject,' ',room), '')) as day4 
  , max(if(day=5, concat(subject,' ',room), '')) as day5 
from schedule 
group by slot 

MAX(...)在一个条目和一个空白之间决定(如果一个条目存在,该条目将获胜),而该组在同一行上排列所有内容。友好警告:如果同一天和时间存在多个条目,您将只能看到按字母顺序排列的条目"更大"。

要查看每个广告位每天安排的课程数量(检查冲突),请尝试:

SELECT slot 
  , sum(if(day=1,1,0)) as day1 
  , sum(if(day=2,1,0)) as day2 
  , sum(if(day=3,1,0)) as day3 
  , sum(if(day=4,1,0)) as day4 
  , sum(if(day=5,1,0)) as day5 
from schedule 
group by slot 

点击此处查看更多解决方案:MySQL pivot table