mysql - how to display all values in multiple columns in SQL query -
i trying display information different tables in database. 1 of these tables called job_pieces. in table there fields id, companyid , piecetype. each company can have many id , piecetypes. not know how many piecetypes each company has. small example companies have 30 piecetypes. here sample database: http://www.sqlfiddle.com/#!9/6d528/2
select c.name, count(distinct jn.id) jobs group_concat(distinct jp.piecetype) allpiecetypes, jp.piecetype piecetype customer c left join job_new jn on c.jobid = jn.id left join job_pieces jp on jn.jobid = jp.jobid c.company_id = compid group c.id
there result of query this:
i added line group_concat
can see piecetypes jobs have. in query need display jobs , piecetypes company has. problem column piecetype. can see in image on first row displaying 1 type, when there should 4. , want each piecetype separate column, this:
splitting allpiecetypes columns separate columns each piece seems difficult thing, searching have done. joining job_pieces table wrong? why 1 type being displayed in piecetype column when more exist? , how can display each piecetype in own column? need in own column because each company has 1 row. need row continue when displaying piecetypes
i found similar here: how parse string , create several columns it? not sure how edit query.
there different approaches can take. real issue need pre-determine how many such types there are. sql queries return fixed set of rows, why group_concat()
convenient.
here illustration of 1 method returns first 3 piece types:
select c.name, count(distinct jn.id) jobs group_concat(distinct jp.piecetype) allpiecetypes, substring_index(group_concat(distinct jp.piecetype order jp.piecttype), ',', 1) piecetype1, substring_index(substring_index(group_concat(distinct jp.piecetype order jp.piecttype), ',', 2), ',', -1) piecetype2, substring_index(substring_index(group_concat(distinct jp.piecetype order jp.piecttype), ',', 3), ',', -1) piecetype3 customer c left join job_new jn on c.jobid = jn.id left join job_pieces jp on jn.jobid = jp.jobid c.company_id = compid group c.id
(if there fewer 3 jobs, logic little bit more complicated, because duplicate values.)
Comments
Post a Comment