Suhandy Chow
Suhandy Chow

Reputation: 259

Merge two columns SQL Server

T1

enter image description here

T2 result from unpivot T1

enter image description here

Unpivot query:

SELECT LocM, convert(varchar,[Date],112) as DateKey, FinanceCode, Amount
FROM SalesDetail
UNPIVOT
   ([Amount] FOR [FinanceCode] IN([Sales],[Wages])) AS P

T3

enter image description here

How to join/merge T2 with T3 so the result will be like:

StoreCode | FinanceCode | DateKey  | Amount
070       | Wages       | 20160131 | 3533
070       | Sales       | 20160131 | 833
070       | 0000        | 20160131 | 0

Upvotes: 2

Views: 276

Answers (1)

Marcin Zukowski
Marcin Zukowski

Reputation: 4739

I assume you want such union of records for all dates, not only for 20160131.

Why don't you simply do UNION ALL on T2 and T3, using proper column ordering?

E.g.

SELECT StoreCode, FinanceCode, DateKey, Amount from T3
UNION ALL
SELECT LocM, FinanceCode, DateKey, Amount from T2

You can wrap it in a subquery and add ORDER BY if you want rows from some category to be next to each other.

Upvotes: 1

Related Questions