SQL Server将两个表合并为一个

时间:2019-08-24 02:15:01

标签: sql-server tsql

我有两个桌子

TBL_PRODUCT_TONNAGE

|      Product        |     Jan          | Feb      | Mar    |
+---------------------+------------------+----------+--------+
|     E5000           |       91234      | 110000   | 10001  |
|     E6000           |       81234      | 120000   | 10002  |
|     E7000           |       71234      | 130000   | 10003  |

TBL_PRODUCT_CALORIE

|      Product        |     Jan          | Feb      | Mar    |
+---------------------+------------------+----------+--------+
|     E5000           |       5010       | 5020     | 5030   |
|     E6000           |       6010       | 6020     | 6030   |
|     E7000           |       7010       | 7020     | 7040   |

是否可以将值合并为以下内容 TBL_PRODUCT_COMBINE

|      Product        |     Jan          | Feb      | Mar    |
+---------------------+------------------+----------+--------+
|     E5000           |       91234      | 110000   | 1001   |
|     E5000_cal       |        5010      |   5020   | 5030   |
|     E6000           |       81234      | 120000   | 1002   |
|     E6000_cal       |        6010      |   6020   | 6030   |
|     E7000           |       71234      | 130000   | 1003   |
|     E7000_cal       |        7010      |   7020   | 7030   |

请咨询

2 个答案:

答案 0 :(得分:2)

使用union all

select    product, jan, feb, mar
from      tbl_product_tonnage

union all
select    product + '_cal', jan, feb, mar
from      tbl_product_calories

您的表吞吐量结构是否可以满足您的报告需求?因为它们没有被标准化,但这确实是一个与所要求的问题不同的问题。

这与union形成对比, ["xxxxx1","xxxxx2","xxxxx3","xxxxx4"] 的作用相同,只是它消除了重复的记录。结果与您的情况相同,但是如果不需要重复数据删除算法,则效率更高。

答案 1 :(得分:0)

select    Product, Jan, Feb, Mar
from      TBL_PRODUCT_TONNAGE
union
select    Product + '_cal', Jan, Feb, Mar
from      TBL_PRODUCT_CALORIE
order by Product