SELECT
DATE_FORMAT(_scan_time, '%Y%m%d') as '日期',
count(_id) as '一天的总量',
count(HOUR(_scan_time)='0' or null ) as '0点',
count(HOUR(_scan_time)='1' or null ) as '1点',
count(HOUR(_scan_time)='2' or null ) as '2点',
count(HOUR(_scan_time)='3' or null ) as '3点',
count(HOUR(_scan_time)='4' or null ) as '4点',
count(HOUR(_scan_time)='5' or null ) as '5点',
count(HOUR(_scan_time)='6' or null ) as '6点',
count(HOUR(_scan_time)='7' or null ) as '7点',
count(HOUR(_scan_time)='8' or null ) as '8点',
count(HOUR(_scan_time)='9' or null ) as '9点',
count(HOUR(_scan_time)='10' or null ) as '10点',
count(HOUR(_scan_time)='11' or null ) as '11点',
count(HOUR(_scan_time)='12' or null ) as '12点',
count(HOUR(_scan_time)='13' or null ) as '13点',
count(HOUR(_scan_time)='14' or null ) as '14点',
count(HOUR(_scan_time)='15' or null ) as '15点',
count(HOUR(_scan_time)='16' or null ) as '16点',
count(HOUR(_scan_time)='17' or null ) as '17点',
count(HOUR(_scan_time)='18' or null ) as '18点',
count(HOUR(_scan_time)='19' or null ) as '19点',
count(HOUR(_scan_time)='20' or null ) as '20点',
count(HOUR(_scan_time)='21' or null ) as '21点',
count(HOUR(_scan_time)='22' or null ) as '22点',
count(HOUR(_scan_time)='23' or null ) as '23点'
FROM
user_GROUP BY
DATE_FORMAT(_scan_time, '%Y%m%d')

解决方案 »

  1.   

    你可以试试这个动态的语句
    SET @@GROUP_CONCAT_MAX_LEN = 1024000;
    set @sql='' ;
    select @sql:= 
    group_concat(
    concat('count(HOUR(_scan_time))=''',number,''' or null as ''',number,' 点''')
    ,'')from sp_values
     where number between 1 and 24;
    set @sql =concat('select DATE_FORMAT(_scan_time, ''%Y%m%d''),',@sql,' from _user group by DATE_FORMAT(_scan_time, ''%Y%m%d'')');
    select @sql表sp_values 里的数据只是编号而已
      

  2.   

    SET @@GROUP_CONCAT_MAX_LEN = 1024000;
    set @sql=NULL ;
    select @sql:= 
    group_concat(
    concat('count(HOUR(_scan_time)=''',number,''' or null )as ''',number,' 点''')
    ,'')
    into @sql
    from sp_values
     where number between 1 and 24;
    set @sql:=concat('select DATE_FORMAT(_scan_time, ''%Y%m%d''),',@sql,' from _user group by DATE_FORMAT(_scan_time, ''%Y%m%d'')');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;