如何使用MAX动态进行SQL查询

时间:2018-09-01 06:07:04

标签: mysql sql max

我有一个这样的SQL查询。如何使其动态化?

SELECT name,  
       MAX(CASE WHEN sub = 'maths'   then 'y' ELSE 'n' END) AS maths,
       MAX(CASE WHEN sub = 'science' then 'y' ELSE 'n' END) AS science,
       MAX(CASE WHEN sub = 'history' then 'y' ELSE 'n' END) AS history,
       MAX(CASE WHEN sub = 'computer'then 'y' ELSE 'n' END) AS computer,
       MAX(CASE WHEN sub = 'english' then 'y' ELSE 'n' END) AS english
FROM table t
GROUP BY name;

所以最终结果是:

   name   maths science history computer    english
    a       y       y       y     y          y
    b       y       y       y     n          n
    c       y       n       y     y          n

还要如何选择y or n作为列值?会选择工作吗?

2 个答案:

答案 0 :(得分:1)

select @cols := group_concat(distinct replace('MAX(CASE WHEN sub = ''[val]''   then ''y'' ELSE ''n'' END) AS `[val]`', '[val]', sub))
from (select distinct sub from t) t;

set @sql = concat('select name, ', @cols,
                  ' from t group by name'
                 );

prepare st from @sql;
execute st;
deallocate prepare st;

答案 1 :(得分:0)

set @sql = (
        select 
        concat('select name,',
        group_concat(
        concat('max(case when sub = ', 
        char(39),s.sub, char(39), ' then ',  char(39),'y',char(39),' else ', char(39),'n',char(39), ' end) as ',s.sub)
        ) 
        ,' from t group by name;')

from
(
select 'math' sub union select 'science' union select 'history'
) s
)
;

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;

+------+------+---------+---------+
| name | math | science | history |
+------+------+---------+---------+
| a    | y    | y       | n       |
| b    | y    | y       | n       |
| c    | y    | n       | y       |
+------+------+---------+---------+
3 rows in set (0.00 sec)

根据需要在并集语句中添加或删除主题。