Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Merge 2 rows into 1

Is it possible to merge 2 rows into a single row in SSRS 2008? Each part will have a record for each site

+---------------+-------+-------+
|Part Number    |Cost   |Site   |
+---------------+-------+-------+
|1              |2.4    |Site 1 |
|1              |68.8   |Site 2 |
+---------------+-------+-------+

Desired Result

+-----------+-------+-------+
|Part Number|Site 1 |Site 2 | 
+-----------+-------+-------+
| 1         |2.4    |68.8   |
+-----------+-------+-------+

Thank you

like image 376
Spacko Avatar asked Mar 26 '13 10:03

Spacko


People also ask

How to combine rows in SQL Server to form a string?

We could use multiple queries to combine rows in SQL Server to form a String. In the below example, we will combine rows using the COALESCE Function. DECLARE @Names VARCHAR (MAX) SELECT @Names = COALESCE (@Names + ', ', '') + [FirstName] FROM [geek_demo] SELECT @Names AS [List of All Names]

How do I merge multiple rows into one row?

The simplest way to merge rows is with an aggregate function such as MIN/MAX. These functions will ignore nulls (see MSDN) and can operate similarly to ISNULL/COALESCE with aggregation. For example: This will return the sample desired results.

When does merge_matched clause return an error in SQL?

When UPDATE is specified in the <merge_matched> clause, and more than one row of <table_source> matches a row in target_table based on <merge_search_condition>, SQL Server returns an error. The MERGE statement can't update the same row more than once, or update and delete the same row.

How do you use merge in a statement?

A. Using MERGE to do INSERT and UPDATE operations on a table in a single statement. A common scenario is updating one or more columns in a table if a matching row exists. Or, inserting the data as a new row if a matching row doesn't exist.


1 Answers

If you know your site numbers/names will not change dynamically then can use CASE WHEN:s

SELECT PartNumber,
MAX(CASE WHEN Site=1 THEN Cost ELSE NULL END) AS Site1_Cost,
MAX(CASE WHEN Site=2 THEN Cost ELSE NULL END) AS Site2_Cost
FROM Parts
GROUP BY PartNumber

By grouping we eliminated a NULL values...

Here link with SQL Fiddle example

like image 165
Fabio Avatar answered Oct 22 '22 02:10

Fabio