I have two sets of tables below:
1:
2:
IputaquerythatreturnstheresultsofthetwotablesusingUnion
:
Selecttbprojeto.projNomeAsProjeto,tbindp.indPNomeAs'Tipo(Ind/Idx)',tbindc.indcValorAsValor,tbproj_cenario.projCenNomeAsCenário,tbidxind_grp.idxIndGrpNomeAs'GrupodeÁnalise'FromtbprojetoInnerJointbindpOntbindp.indPProj_Id=tbprojeto.projIdInnerJointbindcOntbindc.indcInd_Id=tbindp.indPIdInnerJointbproj_cenarioOntbproj_cenario.projCenProj_Id=tbprojeto.projIdAndtbindc.indcCen_Id=tbproj_cenario.projCenIdInnerJointbidxind_grpOntbindp.indPIdxIndGrp_Id=tbidxind_grp.idxIndGrpIdUnionSelecttbprojeto.projNomeAsProjeto,tbidxp.idxPNomeAs'Tipo(Ind/Indx)',tbidxc.IdxCValorAsValor,tbproj_cenario.projCenNomeAsCenário,tbidxind_grp.idxIndGrpNomeFromtbprojetoInnerJointbidxpOntbidxp.idxPProj_Id=tbprojeto.projIdInnerJointbidxcOntbidxc.IdxCIdx_Id=tbidxp.idxPIdInnerJointbproj_cenarioOntbproj_cenario.projCenProj_Id=tbprojeto.projIdAndtbidxc.IdxCProjCen_Id=tbproj_cenario.projCenIdInnerJointbidxind_grpOntbidxp.idxPIdxIndGrp_Id=tbidxind_grp.idxIndGrpId
Here'stheresult:
I'mtryingtopivotthisqueryspecificallysothateachvalueinthescenariocolumnisanewcolumnwithjoinwiththeValuecolumn,theresultwouldlooksomethinglikethis:
Aftermuchworkandhelpfromthestaff,Igotthis(below)withthiscode:
SET@sql=NULL;SELECTGROUP_CONCAT(DISTINCTCONCAT('casewhenprojCenNome="',
projCenNome,
'" then indcValor end AS \'',
projCenNome, '\''
)
) INTO @sql
from (select projCenNome from tbproj_cenario
inner join tbindc on tbindc.indcCen_Id = tbproj_cenario.projCenId
) A;
SET @sql = CONCAT('Select tbindp.'indPNome' As Valor , ', @sql, '
From tbindc
Inner Join
tbproj_cenario On tbindc.indcCen_Id = tbproj_cenario.projCenId
Inner Join
tbindp On tbindc.indcInd_Id = tbindp.indPId');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
That is, the values of the other columns, in the Name case, are not transposed, thus repeating, how could I circumvent this?