Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two rows with same id but different column values into one row [mysql]

Tags:

sql

mysql

I have joined two tables and obtained a resultset that has different rows for the same id or say, type, but they have different column values.

Eg.

leave_type  |  max Days  |  jan  |  feb  |  mar  |  apr
Personal    |  12        |  0.00 |  0.00 |  2.00 |  0.00
Personal    |  12        |  1.00 |  0.00 |  0.00 |  0.00
Sick        |  5         |  0.00 |  0.00 |  1.00 |  0.00

I would like the result as follows:

leave_type  |  max Days  |  jan  |  feb  |  mar  |  apr
Personal    |  12        |  1.00 |  0.00 |  2.00 |  0.00
Sick        |  5         |  0.00 |  0.00 |  1.00 |  0.00

How can this be done in mysql?

Any help is very much appreciated. Thanks.

like image 771
Azima Avatar asked Sep 07 '25 11:09

Azima


2 Answers

You can use GROUP BY and aggregate functions.

SELECT
    `leave_type`,
    MAX(`days`) AS `max_days`,
    MAX(`jan`) AS `jan`,
    MAX(`feb`) AS `feb`,
    MAX(`mar`) AS `mar`,
    MAX(`apr`) AS `apr`
FROM
    `table`
GROUP BY
    `leave_type`

It's not clear whether you want to use MAX or SUM from your example, but you can use either, depending on your goal.

like image 130
kchason Avatar answered Sep 09 '25 04:09

kchason


You can just use an aggregation query:

select leave_type, maxDays,
       sum(jan) as jan, sum(feb) as feb, sum(mar) as mar, sum(apr) as apr
from t
group by leave_type, maxDays ;
like image 42
Gordon Linoff Avatar answered Sep 09 '25 03:09

Gordon Linoff