Home > Database > Mysql Tutorial > How Can I Efficiently Merge Rows in SQL to Combine Data?

How Can I Efficiently Merge Rows in SQL to Combine Data?

DDD
Release: 2024-12-31 13:50:10
Original
883 people have browsed it

How Can I Efficiently Merge Rows in SQL to Combine Data?

Merging Rows Efficiently in SQL

In SQL, it is often required to combine information from multiple rows into a single consolidated row. Consider the following table:

FK | Field1 | Field2
=====================
3  | ABC    | *NULL*
3  | *NULL* | DEF
Copy after login

To obtain a merged row, it is possible to utilize aggregate functions such as MAX or MIN. These functions ignore NULL values, allowing us to combine non-null values from different rows.

The following query demonstrates the use of the MAX aggregate function to merge the two rows:

SELECT
    FK,
    MAX(Field1) AS Field1,
    MAX(Field2) AS Field2
FROM
    table1
GROUP BY
    FK;
Copy after login

In SQL Server Express 2008 R2, this query produces the following result:

FK  Field1  Field2
--  ------  ------
3   ABC     DEF
Copy after login

This query effectively merges the two rows into a single consolidated row, preserving the FK column and combining the non-null values for Field1 and Field2.

The above is the detailed content of How Can I Efficiently Merge Rows in SQL to Combine Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template