1

My join query looks like this:

select distinct A.id as plan_id, A.start_date, A.end_date, C.title 
from cp_plan A left outer join cp_plan_zone_map B 
on A.id = B.plan_id left outer join cp_zone C 
on B.zone_id = C.id where A.status = 'in-planning'  

This gives me the following result:

enter image description here

Since my plan id, start date and end date are all same, all I want is to merge the title like this:

enter image description here

How can I achieve this?

  • 1
    Did you try `pivot` ? [check this](https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – dwij Oct 02 '17 at 04:38
  • Nice description here aswell. However, I find easier to implement GROUP_CONCAT() func but thanks for the suggestion! –  Oct 02 '17 at 04:50

2 Answers2

2

Aggregate over the plan_id, start_date, and end_date, and use GROUP_CONCAT to generate the hyphen separated list of titles:

SELECT
    A.id AS plan_id,
    A.start_date,
    A.end_date,
    GROUP_CONCAT(C.title, '-') AS title
FROM cp_plan A
LEFT JOIN cp_plan_zone_map B 
    ON A.id = B.plan_id
LEFT JOIN cp_zone C 
    ON B.zone_id = C.id
WHERE
    A.status = 'in-planning'
GROUP BY
    A.id,
    A.start_date,
    A.end_date;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Found an answer here:

SELECT A.id AS plan_id,
       A.start_date,
       A.end_date,
       group_concat(C.title, '-') AS title
FROM cp_plan A
LEFT OUTER JOIN cp_plan_zone_map B ON A.id = B.plan_id
LEFT OUTER JOIN cp_zone C ON B.zone_id = C.id
WHERE A.status = 'in-planning'
GROUP BY plan_id   
zarruq
  • 2,445
  • 2
  • 10
  • 19