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

问题描述 投票:-2回答:2

我有这样的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作为列值?会选择工作吗?

mysql sql max
2个回答
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;

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)

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

© www.soinside.com 2019 - 2024. All rights reserved.