简体   繁体   中英

Combine multiple MySQL rows into one row

Here's what I am currently getting from my query:

row_no prospect hot contract
1 null Joe null
1 John null null
1 null null Sam

I Am trying to get:

row_no prospect hot contract
1 John Joe Sam

I cannot use concate because I still need separate columns

Here's what I have so far...
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e7aab240b40e40955bac44f616d7f3d7

Please note: Ultimately, there will be 7 columns, but a varying amount of rows (ie. the prospect column may have 20 records, where the contract column may only have four or five.

You can do it with conditional aggregation:

WITH CTE_tbl AS
(
  SELECT lead_type,firstname, last_date,
         ROW_NUMBER() OVER(PARTITION BY lead_type order by lead_type Desc) as row_no
  FROM leads
) 
SELECT row_no,
       MAX(case when  lead_type = 'prospect' then firstname end) prospect,
       MAX(case when  lead_type = 'hot' then firstname end) hot,
       MAX(case when  lead_type = 'contract' then firstname end) contract
FROM CTE_tbl
GROUP BY row_no
ORDER BY row_no

See the demo .
Results:

row_no prospect hot contract
1 John Joe Sam
2 Mario Autumn null
3 Frank null null
4 Mary null null
5 Steve null null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM