我有一张 table :
如上图所示,还有许多其他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;
但无法获得所需的输出,只有一列值,如下所示:
实际上,在第 59 行 meta_appl_id 中,它必须显示 Ph - 是、农村 - 是和 Woman 是,但它只显示在 Woman 中(因为它是查询中的最后一个 if 语句)。
最佳答案
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 列。
关于php - 基于具有不同值的相同列名创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32975782/