在一个简单的行转列上居然遇见问题,就是字段d是一个datetime类型的,要和日期进行比较,写成如下形式:
select AA,@dd:=DATE(d) ,
max(case @dd when '2011-12-26' then a end) '',
max(case @dd when '2011-12-26' then b end) '',
max(case @dd when '2011-12-26' then c end) '',
max(case @dd when '2011-12-27' then a end) '',
max(case @dd when '2011-12-27' then b end) '',
max(case @dd when '2011-12-27' then c end) '',
max(case @dd when '2011-12-28' then a end) '',
max(case @dd when '2011-12-28' then b end) '',
max(case @dd when '2011-12-28' then c end) ''
from A
group by AA;
目的是我想为了省去对DATETIME类型的d列的转换,这个语句居然是错误的,得不到想要的结果 。换成下面的这个结果倒是正确了,但是好像每次都要对d列进行转换是不是太浪费了,当然如果把d列改成DATE类型不存在这个问题,但问题上是原先使用的系统不可能一下子改过来,还有有没有更好的转换方式呢。以及造成上面和下面两个语句不一样的原因,应该是SQL对聚合函数的处理顺序的原因吧,这个也不深究了。
select AA,@dd:=d ,
max(case DATE(d) when '2011-12-26' then a end) '',
max(case DATE(d) when '2011-12-26' then b end) '',
max(case DATE(d) when '2011-12-26' then c end) '',
max(case DATE(d) when '2011-12-27' then a end) '',
max(case DATE(d) when '2011-12-27' then b end) '',
max(case DATE(d) when '2011-12-27' then c end) '',
max(case DATE(d) when '2011-12-28' then a end) '',
max(case DATE(d) when '2011-12-28' then b end) '',
max(case DATE(d) when '2011-12-28' then c end) ''
from A
group by AA;