我有两个带有相同数据的表,我需要比较一列,这里是用于测试的ddl
USE [DifferencesDB]
GO
/****** Object: Table [dbo].[FirstTable] Script Date: 11/06/2019 15:27:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FirstTable](
[Id] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Column4] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[FirstTable] ([Id], [Column1], [Column2], [Column4]) VALUES (1, N'test ', N'test ', 30)
GO
INSERT [dbo].[FirstTable] ([Id], [Column1], [Column2], [Column4]) VALUES (2, N'test2 ', N'test3 ', 18)
GO
CREATE TABLE [dbo].[SecondTable](
[Id] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Column4] [decimal](18, 5) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[SecondTable] ([Id], [Column1], [Column2], [Column4]) VALUES (1, N'test ', N'test ', 13.56895)
GO
INSERT [dbo].[SecondTable] ([Id], [Column1], [Column2], [Column4]) VALUES (2, N'test2 ', N'test3 ', 18.456 )
GO
正如您在此处看到的,我要比较的是两个表和第4列中的数据(十进制)。
/****** Script for SelectTopNRows command from SSMS ******/
SELECT ABS(T0.Column4 -T1.Column4) as 'Difference'
FROM [FirstTable] T0, [SecondTable] T1
where T0.Id =T1.ID
这行得通,但它给了我额外行的色调,这使我获得了所需的区别,因此如何从其他表中排除行。
例如,应该说的区别是我希望从第二个表中返回数据,但也希望从差异表中返回数据。
.456
修改 展示实时数据中发生的事情。
请在此处查看我的新查询
SELECT GoodData_Lines.Qty,
Invalid_Lines.Qty,
abs(GoodData_Lines.Qty- Invalid_Lines.Qty) AS 'Difference'
FROM GoodData_Lines
left OUTER JOIN Invalid_MCSSOPLines
ON GoodData_Lines.LineID = Invalid_Lines.LineID
答案 0 :(得分:0)
这可以解决吗? [EDIT]更新后
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[GoodData_Lines](
[LineID] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Qty] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[GoodData_Lines] ([LineID], [Column1], [Column2], [Qty]) VALUES (1, N'test ', N'test ', 30)
GO
INSERT [dbo].[GoodData_Lines] ([LineID], [Column1], [Column2], [Qty]) VALUES (2, N'test2 ', N'test3 ', 18)
GO
CREATE TABLE [dbo].[Invalid_MCSSOPLines](
[LineID] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Qty] [decimal](18, 5) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Invalid_MCSSOPLines] ([LineID], [Column1], [Column2], [Qty]) VALUES (1, N'test ', N'test ', 13.56895)
GO
INSERT [dbo].[Invalid_MCSSOPLines] ([LineID], [Column1], [Column2], [Qty]) VALUES (2, N'test2 ', N'test3 ', 18.456 )
GO
SELECT GoodData_Lines.Qty,
isnull( [Invalid_MCSSOPLines].Qty,0) invalid_qty,
abs(GoodData_Lines.Qty - isnull([Invalid_MCSSOPLines].Qty,0)) AS 'Difference'
FROM GoodData_Lines
left OUTER JOIN Invalid_MCSSOPLines
ON GoodData_Lines.LineID = [Invalid_MCSSOPLines].LineID
-- eventually drop table if no more needed
-- DROP TABLE [GoodData_Lines]
-- DROP TABLE [Invalid_MCSSOPLines]
答案 1 :(得分:0)
不太清楚问题是什么,但是根据我的理解,这会解决吗?
SELECT T1.*, ABS(T0.Column4 -T1.Column4) as 'Difference'
FROM [FirstTable] T0 right join [SecondTable] T1
on T0.Id =T1.ID