我有2个名为'确定'和'TX'的数据库,它们具有名为'E_Model '的相同表,并具有以下列: “产品ID”,“说明”,“保修”和“类别” 我想拥有两个表都具有的产品ID的列表,并且想同时知道所有其他列的差异。
所需结果应类似于:
**'*Database' 'Product_ID' , 'Description', 'Warranty' 'Category'***
OK LB9456 COFFEE 436 NULL 10
TX LB9456 TOASTER 956 1 12
OK QR3300 APPLE 31 3 15
TX QR3300 ORANGE 45 5 20
我尝试运行以下查询:
SELECT Product_ID
FROM OKSV..E_MODEL
INTERSECT
SELECT Product_ID
FROM TXSV..E_MODEL
union all
SELECT Product_ID
FROM TXSV..E_MODEL
INTERSECT
SELECT Product_ID
FROM OKSV..E_MODEL
我确实在不同数据库的两个表中都获得了类似Product_ID的列表。但是当我使用以下查询时:
SELECT Product_ID, Description, Warranty, Category
FROM OKSV..E_MODEL
INTERSECT
SELECT Product_ID,Description, Warranty, Category
FROM TXSV..E_MODEL
union all
SELECT Product_ID,Description, Warranty, Category
FROM TXSV..E_MODEL
INTERSECT
SELECT Product_ID
FROM OKSV..E_MODEL
它向我显示了一个不同的列表。基本上,我试图了解两个表中相似产品ID的描述,类别和保修的差异。 我这样做是为了清理数据。我是新来的,请帮忙,因为我现在一个接一个地做,这将需要很多时间。
答案 0 :(得分:0)
这是执行此操作的一种方法(现在与更新的规范匹配)。我为此有两个独立的CTE,因为它应该使我在做的事情更清楚,但是使用其他查询也可以完成同样的事情。
WITH TXInfo AS ( -- Get all info from TX DB with ID matches
SELECT Product_ID,
Description,
Warranty,
Category
FROM TXSV..E_MODEL
WHERE Product_ID IN (
SELECT Product_ID
FROM OKSV..E_MODEL
INTERSECT
SELECT Product_ID
FROM TXSV..E_MODEL
)
),
MisMatches as ( -- Get all info from OK DB with data mismatches
SELECT
om.Product_ID,
om.Description,
om.Warranty,
om.Category
FROM OKSV..E_MODEL om
INNER JOIN TxInfo ti
ON om.Product_ID = ti.Product_ID
WHERE om.Description <> ti.Description
OR om.Warranty <> ti.Warranty
OR om.Category <> ti.Category
)
SELECT 'OK' as [Database], -- Select all OK data
mm.Product_Id,
mm.Description,
mm.Warranty,
mm.Category
FROM Mismatches mm
UNION
SELECT 'TX', -- Select only TX data that didn't match
ti.Product_Id,
ti.Description,
ti.Warranty,
ti.Category
FROM TXInfo ti
INNER JOIN Mismatches mm
ON ti.Product_Id = mm.Product_Id
ORDER BY Product_Id,
1 desc -- Will not let us order by the name of the field here.