合并两列SQL Server

时间:2016-08-19 03:51:00

标签: sql sql-server database

T1

enter image description here

T2来自unpivot T1

enter image description here

取消透视查询:

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

如何将T2与T3连接/合并,结果如下:

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

1 个答案:

答案 0 :(得分:1)

我假设你想要所有日期的记录联合,不仅仅是20160131。

为什么不使用正确的列排序在T2和T3上执行UNION ALL?

E.g。

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

如果您希望某个类别中的行彼此相邻,则可以将其包装在子查询中并添加ORDER BY