I am trying to display some information from different tables in a database. One of these tables is called job_pieces. In this table there are fields ID, CompanyID and PieceType. Each company can have many ID and PieceTypes. I will not know how many PieceTypes each company has. This is just a small example but some companies have nearly 30 PieceTypes. Here is a sample database: http://www.sqlfiddle.com/#!9/6d528/2
SELECT c.Name,
COUNT(distinct jn.ID) as Jobs
GROUP_CONCAT(DISTINCT jp.PieceType) as AllPieceTypes,
jp.PieceType as PieceType
FROM customer c
LEFT JOIN job_new jn ON c.JobID = jn.ID
LEFT JOIN job_pieces jp ON jn.JobID = jp.JobID
WHERE c.Company_ID = compid
GROUP BY c.ID
There result of this query is this:
I added the line GROUP_CONCAT
so you can see all the PieceTypes the jobs have.
So in this query I need to display all the jobs and PieceTypes a company has. The problem is with the column PieceType. As you can see in the image on the first row it is only displaying one type, when there should be 4. And I also want each PieceType to be a separate column, something like this:
Splitting the AllPieceTypes columns into separate columns for each piece seems to be a difficult thing, from the searching I have done. So am I joining the job_pieces table wrong? Why is only one type being displayed in the PieceType column when more exist? And how can I display each PieceType in its own column? They need to be in their own column because each company only has one row. So I need the row to continue when displaying PieceTypes
I found something similar here: How to parse a string and create several columns from it? But I am not sure how to edit this for my query.