合并sql中的列然后标识源列

时间:2017-02-24 18:42:10

标签: sql-server

我希望查询此表,将每两列的数据合并为1(Material1 + Material2,Quantity1 + Quantity2,Time1 + Time2),另一行用于标识材料(如果它是Material1或Material2)

输入数据:

enter image description here

期望的输出:

desired Output table

我试过了:

SELECT Material1 as Material 
FROM [test] 
UNION all 
SELECT Material2 
FROM [test]

SELECT [Quantity1] as Quantity 
FROM [test] 
Union all 
Select Quantity2 
FROM [test] 
ORDER BY Quantity1

但事实证明是在两个表格中。

1 个答案:

答案 0 :(得分:1)

也许是这样的?

select 'Material1' as Name
      ,Material1 as Material
      ,Quantity1 as Quantity
      ,Time1 as [Time]
from   [test]

union all

select 'Material2' as Name
      ,Material2 as Material
      ,Quantity2 as Quantity
      ,Time2 as [Time]
from   [test]