我有一张桌子:
如上图所示,还有许多其他meta_appl_id。
现在,我想运行一个SQL查询,以便根据“ meta_value”的值创建列。我试过了:
SELECT * ,
if (`meta_value` = 'physically challenged' , 'yes', '') as PH,
if (`meta_value` = 'kannada medium' , 'yes', '') as Kannada,
if (`meta_value` = 'rural' , 'yes', '') as rural,
if (`meta_value` = 'woman' , 'yes', '') as woman
FROM `applicant_meta` WHERE `meta_value` = 'physically challenged' or `meta_value` = 'woman' group by meta_appl_id;
但无法获得所需的输出,只有一个列值,如下所示:
实际上,在meta_appl_id 59行中,它必须显示Ph-是,农村-是,并且是yes,但是仅在woman中显示(因为如果查询中的语句是最后一个,则该字段)。
最佳答案
SELECT meta_appl_id, if(PH= 0, 'no', 'yes'), if(WOMAN= 0, 'no', 'yes')
FROM (
SELECT meta_appl_id
, (select count(1) FROM applicant_meta as innertab where UPPER(innertab.meta_appl_id) = UPPER(aa.meta_appl_id) and UPPER(meta_value)=UPPER('physically challenged')) as PH
, (select count(1) FROM applicant_meta as innertab where innertab.meta_appl_id = aa.meta_appl_id and UPPER(meta_value)='WOMAN') as WOMAN
FROM applicant_meta as aa
GROUP BY meta_appl_id
) as bb;
请根据需要添加其他可能的列。我在这里显示了2列。