How can I combine multiple rows into one row so that some of the columns in one row replace null values in the same columns in the other row it is being merged with? Here’s an example of what I have and what I’m trying to achieve. The query is:
SELECT Drug. Name,
DefaultVendor.Name,
Drug.Strength,
Catalog.DIN,
Catalog.PackSize,
“Vendor1 Price” = CASE WHEN Ven.Name = ‘Vendor1’ THEN Catalog.Price ELSE NULL END,
“Vendor1 ItemNum” = CASE WHEN Ven.Name = ‘Vendor1’ THEN Catalog.ItemNum ELSE NULL END,
“Vendor2 Price” = CASE WHEN Ven.Name = ‘Vendor2’ THEN Catalog.Price ELSE NULL END,
“Vendor2 ItemNum” = CASE WHEN Ven.Name = ‘Vendor2’ THEN Catalog.ItemNum ELSE NULL END
FROM Catalog INNER JOIN
Drug ON Catalog.DIN = Drug.DIN INNER JOIN
Vendor AS Ven ON Ven.ID = Catalog.VendorID LEFT JOIN
Vendor AS DefaultVendor ON DefaultVendor.ID = Catalog.DefVendorID OR (DefaultVendor.ID IS NULL)
WHERE Catalog.Description LIKE ‘Acetaminophen%’
GROUP BY Ven.Name,
Drug.Name,
Drug.Strength,
Catalog.DIN,
Catalog.PackSize,
Catalog.Price,
Catalog.ItemNum
ORDER BY Drug.Strength
The result this spits out looks like this:
| Name | DefaultVendor | Strength | DIN | PackSize | Vendor1Price | Vendor1ItemNum | Vendor2Price | Vendor2ItemNum |
|---------------|---------------|----------|-----|----------|--------------|----------------|--------------|----------------|
| Acetaminophen | Vendor1 | 325mg | 1 | 100 | 5 | 1234 | (null) | (null) |
| Acetaminophen | Vendor1 | 325mg | 1 | 200 | 9 | 1235 | (null) | (null) |
| Acetaminophen | Vendor1 | 325mg | 1 | 100 | (null) | (null) | 5.25 | 1111 |
| Acetaminophen | Vendor1 | 325mg | 1 | 200 | (null) | (null) | 10 | 1122 |
| Acetaminophen | Vendor1 | 500mg | 2 | 100 | 7 | 1236 | (null) | (null) |
| Acetaminophen | Vendor1 | 500mg | 2 | 200 | 13 | 1237 | (null) | (null) |
| Acetaminophen | Vendor1 | 500mg | 2 | 100 | (null) | (null) | 7.5 | 1133 |
| Acetaminophen | Vendor1 | 500mg | 2 | 200 | (null) | (null) | 14 | 1144 |
So I know the data is there. What I want to do is combine the rows with the same strength and packsize so that a single row will display the price and item number from both vendors. Below is the result I am looking for:
| Name | DefaultVendor | Strength | DIN | PackSize | Vendor1Price | Vendor1ItemNum | Vendor2Price | Vendor2ItemNum |
|---------------|---------------|----------|-----|----------|--------------|----------------|--------------|----------------|
| Acetaminophen | Vendor1 | 325mg | 1 | 100 | 5 | 1234 | (null) | (null) |
| Acetaminophen | Vendor1 | 325mg | 1 | 200 | 9 | 1235 | (null) | (null) |
| Acetaminophen | Vendor1 | 325mg | 1 | 100 | (null) | (null) | 5.25 | 1111 |