SQL Server:如何获取比较两个表以及不应比较的另一列的额外记录

时间:2018-11-15 12:00:43

标签: sql-server-2014

这是我的样本数据

INSERT INTO MA_NewRevised VALUES 
       ('Vishal','SD','Col',2),
        ('Shivu','SD','Col',3),
        ('Pavithra','SD','Col',4),
        ('Keerthi','SD','Col',5),
        ('Bharath','SD','Col',6),
        ('Radhu','SD','Col',2),
        ('Vanitha','SD','Col',3),
        ('Anirudh','SD','Col',4),
        ('Amit','SD','Col',5)

         INSERT INTO MA_OldValues VALUES 
       ('Vishal','SD','Col',2),
        ('Shivu','SD','Col',3),
        ('Pavithra','SD','Col',2),
        ('Keerthi','SD','Col',3),
        ('Bharath','SD','Col',6),
        ('Radhu','SD','Col',2),
        ('Vanitha','SD','Col',3),
        ('Raju','SD','Col',1)

第一个代码:

SELECT * FROM MA_NewRevised n
EXCEPT
SELECT * FROM MA_OldValues o

上面的代码会给我。

Except Values

第二个代码

SELECT Name,Groups,CommonColumn FROM MA_NewRevised 
        EXCEPT
        SELECT Name,Groups,CommonColumn FROM MA_OldValues 

以上代码将给我:

Except without Quantity

但是所需的输出是

Except without Quantity, but output with Qty

即,应选择与名称,组,CommonColumn有关的不同值以及新修订表(第一个表)的数量

1 个答案:

答案 0 :(得分:0)

对于您的查询,该查询将不返回额外的列,但返回正确的行,请联接原始表并检索额外列的值。由于您的数据中没有唯一字段,因此您可能必须加入所有字段。

;with cte as (
SELECT Name,Groups,CommonColumn FROM MA_NewRevised 
EXCEPT
SELECT Name,Groups,CommonColumn FROM MA_OldValues
)
select cte.*, n.Quatity -- or n.Quantity, not sure which is the correct name of your column
from cte
inner join MA_NewRevised n on cte.Name = n.Name and cte.Groups = n.Groups and cte.CommonColumn = n.CommonColumn