简体   繁体   English

将具有相同id但不同列值的两行合并为一行[mysql]

[英]merge two rows with same id but different column values into one row [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. 我已经加入了两个表并获得了一个结果集,该结果集对于相同的id或者说类型有不同的行,但是它们具有不同的列值。

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? 怎么能在mysql中完成?

Any help is very much appreciated. 很感谢任何形式的帮助。 Thanks. 谢谢。

You can use GROUP BY and aggregate functions. 您可以使用GROUP BY和聚合函数。

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. 目前尚不清楚您是否要在示例中使用MAXSUM ,但您可以使用其中任何一个,具体取决于您的目标。

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 ;

Try aggregating by leave type and taking the sum of the month columns: 尝试按假类型汇总并获取月份列的总和:

SELECT
    leave_type,
    MAX(`max Days`) AS max_days,
    SUM(jan) AS jan,
    SUM(feb) AS feb,
    SUM(mar) AS mar,
    SUM(apr) AS apr
FROM yourTable
GROUP BY leave_type;

It is not clear whether the max days would always be the same for a given leave type. 目前尚不清楚特定假期类型的最大天数是否总是相同。 In any case, I arbitrarily retain the maximum value. 无论如何,我随意保留最大值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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