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
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;
In SQL Server Express 2008 R2, this query produces the following result:
FK Field1 Field2 -- ------ ------ 3 ABC DEF
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!