我正在尝试将来自两个不同表结构的数据合并到一个查询中。我认为可以做到,但我对语法和方法感到迷茫。以下是我的两个表的结构:表1和表2.表1是以前的旧数据。新数据放在不同的结构中,表2.实际值仍然相同,有两种收入类型,可以为其分配三种业务类型。表2不再需要BusinessTypeC
,因此不包括在内。表1中的BusinessTypeA
和BusinessTypeB
只是表2中的BusinessType
1和2。
我知道UNION
查询中的数据,因为数据不重叠。但是我如何在查询中创建一个新的数据集,基本上重建表1,如表2,所以他们可以UNION
并成为一个查询数据集?
任何想法或指向我正确的方向非常感谢。如果您需要更多细节,请告诉我!我有另外几张这样的桌子,但同样的问题。所以我可以在其他地方申请帮助!
ReturnsID
和SubmissionID
是双主键。对不起,我会提供一些示例数据,但我不知道如何标记或包含它!
表1结构:
>CREATE TABLE [dbo].[RevenueOLD](
[ReturnsID] [int] NOT NULL,
[SubmissionId] [int] NOT NULL,
[RevenueType] [int] NOT NULL,
[BusinessTypeA] [numeric](13, 2) NULL,
[BusinessTypeB] [numeric](13, 2) NULL,
[BusinessTypeC] [numeric](13, 2) NULL
表2结构:
>CREATE TABLE [dbo].[RevenueNEW](
[ReturnsID] [int] NOT NULL,
[SubmissionId] [int] NOT NULL,
[RevenueType] [int] NOT NULL,
[BusinessType] [int] NOT NULL,
[Value] [numeric](13, 2) NULL
答案 0 :(得分:0)
也许是这样的:
SELECT
ReturnsID,
SubmissionId,
RevenueType,
BusinessTypeA,
BusinessTypeB,
BusinessTypeC,
NULL AS BusinessType,
NULL AS Value
FROM
RevenueOLD
UNION ALL
SELECT
ReturnsID,
SubmissionId,
RevenueType,
NULL AS BusinessTypeA,
NULL AS BusinessTypeB,
NULL AS BusinessTypeC,
BusinessType,
Value
FROM
RevenueNEW
答案 1 :(得分:0)
由于您需要来自RevenueNEW的结构,我认为您需要将其查询与来自RevenueOLD的三个(或两个,如果您不关心BusinessTypeC)查询联合起来:
SELECT *
FROM RevenueNEW
UNION ALL
SELECT ReturnsID, SubmissionId, RevenueType,
1 AS BusinessType, BusinessTypeA AS Value
FROM RevenueOLD WHERE ISNULL(BusinessTypeA, 0) <> 0
UNION ALL
SELECT ReturnsID, SubmissionId, RevenueType,
2 AS BusinessType, BusinessTypeB AS Value
FROM RevenueOLD WHERE ISNULL(BusinessTypeB, 0) <> 0
UNION ALL
SELECT ReturnsID, SubmissionId, RevenueType,
3 AS BusinessType, BusinessTypeC AS Value
FROM RevenueOLD WHERE ISNULL(BusinessTypeC, 0) <> 0