【问题标题】:Merging tables with duplicate data合并具有重复数据的表
【发布时间】:2012-10-17 06:02:14
【问题描述】:

对于 SQL Server 数据仓库,我需要匹配 2 个包含大致相同数据的表。

显然不止于此,因此重新定义任务不是一种选择:-)

给定 2 个表,A 和 B

表 A:

id  | fid | type
-------------------
100 | 1   | cookies
110 | 1   | muffins
120 | 1   | muffins

表 B:

id   | fid | type
--------------------
a220 | 1   | muffins
b220 | 1   | muffins

当合并时(在这里应用秘密 IT - SQL),它应该变成

A_B:

A_id | B_id | fid | type
---------------------------
100  | NULL | 1   | cookies
110  | a220 | 1   | muffins
120  | b220 | 1   | muffins

任何使用 T-SQL 的解决方案都是首选,性能不是问题。如果 SSIS 是一个更简单的选择,我可以接受。


这是一个用于创建测试环境的脚本供您使用。

/****** Object:  Table [dbo].[B]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[B](
    [id] [varchar](10) NULL,
    [fid] [int] NULL,
    [type] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[B] ([id], [fid], [type]) VALUES (N'a220', 1, N'muffins')
INSERT [dbo].[B] ([id], [fid], [type]) VALUES (N'b220', 1, N'muffins')
/****** Object:  Table [dbo].[A]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[A](
    [id] [varchar](10) NULL,
    [fid] [int] NULL,
    [type] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[A] ([id], [fid], [type]) VALUES (N'100', 1, N'cookies')
INSERT [dbo].[A] ([id], [fid], [type]) VALUES (N'110', 1, N'muffins')
INSERT [dbo].[A] ([id], [fid], [type]) VALUES (N'120', 1, N'muffins')

【问题讨论】:

  • 为什么a.110匹配a220?
  • 您要加入“类型”字段中的表格吗?

标签: sql sql-server data-warehouse


【解决方案1】:

假设您要匹配 ID 的类型和顺序...

select a.id, b.id, ISNULL(a.fid,b.fid) fid, ISNULL(a.type,b.type) type
from
    (select *, ROW_NUMBER() over (partition by type order by id) rn from a ) a
        full outer join
    (select *, ROW_NUMBER() over (partition by type order by id) rn from b ) b
        on a.rn=b.rn
        and a.type = b.type
order by a.id       

【讨论】:

  • 这太优雅了,太漂亮了。我向 SQL Master 鞠躬 :-)
猜你喜欢
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 2015-02-10
  • 2016-09-09
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
相关资源
最近更新 更多