nirosha rathnayaka
nirosha rathnayaka

Reputation: 198

Need help to generate report using php mysql

I want to join two MySQL tables on processID and get following out put as the report.

table 1: LMProcess
------------------------------------
| ProcessID | LMNo | Status | Dept | 
------------------------------------
|1          |1001  |1       |Legal |
|2          |1001  |1       |R&D   |
|3          |1001  |1       |D&R   |
|4          |1001  |1       |L&M   |
|5          |1002  |1       |Legal |
|6          |1002  |1       |R&D   |
|7          |1002  |1       |D&R   |
|8          |1002  |1       |L&M   |
------------------------------------

table 2: Recommendation
-----------------------------------
| ID | ProcessID | Recommendation |
-----------------------------------
|    |1          |Yes             |
|    |2          |No              |
|    |3          |Yes             |
|    |4          |Yes             |
|    |5          |Yes             |
|    |6          |No              |
|    |7          |No              |
|    |8          |Yes             |
-----------------------------------

Report: LM File Recommendations by the Departments
----------------------------------
| LMNo | Legal | R&D | D&R | L&M |
----------------------------------
|1001  |Yes    |No   |Yes  |Yes  |
|1002  |Yes    |No   |No   |Yes  |
----------------------------------

Upvotes: 0

Views: 705

Answers (1)

eggyal
eggyal

Reputation: 125855

You're attempting to perform a pivot operation, which is something that some other RDBMS support natively but MySQL does not (as the developers feel it is something that really belongs in the presentation layer, rather than the database).

However, you can group your results by LMNo and use MySQL's GROUP_CONCAT() function to achieve the desired results:

SELECT   LMNo
       , GROUP_CONCAT(IF(Dept='Legal', Recommendation, NULL)) AS `Legal`
       , GROUP_CONCAT(IF(Dept='R&D'  , Recommendation, NULL)) AS `R&D`
       , GROUP_CONCAT(IF(Dept='D&R'  , Recommendation, NULL)) AS `D&R`
       , GROUP_CONCAT(IF(Dept='L&M'  , Recommendation, NULL)) AS `L&M`
FROM     LMProcess JOIN Recommendation USING (ProcessID)
GROUP BY LMNo

Upvotes: 1

Related Questions