比较两个表,找到不匹配的价格SQL Server

时间:2017-04-11 09:36:18

标签: sql sql-server

create table #tmp1
( 
     name varchar(100),
     price decimal(10, 2)
)

insert into #tmp1 values('Test', 200.00)
insert into #tmp1 values('Test', 100.00)
insert into #tmp1 values('Test', 300.00)
insert into #tmp1 values('Test1', 500.00)
insert into #tmp1 values('Test2', 300.00)

create table #tmp
(
     name varchar(100),
     price decimal(10,2)
)

insert into #tmp values('Test', 200.00)
insert into #tmp values('Test', 100.00)
insert into #tmp values('Test', 400.00)
insert into #tmp values('Test1', 600.00)
insert into #tmp values('Test3', 300.00)

我有两个表,比较参数名称,找不到匹配的价格。 名称应该匹配,价格会有所不同。

预期产出:

Name    Price       Price
------------------------------
Test1   600.00      500.00
Test    300.00      400.00

1 个答案:

答案 0 :(得分:2)

试试这个

SELECT * 
FROM #tmp a
INNER JOIN #tmp1 b ON a.name=b.name AND a.PRICE <> b.PRICE

更新:根据您的以下评论,您也要考虑插入顺序,

;WITH tmp AS (
  SELECT *,
         ROW_NUMBER() OVER(PARTITION BY NAME ORDER BY NAME) RN    
  FROM #tmp 
),tmp1 AS (
  SELECT *,
         ROW_NUMBER() OVER(PARTITION BY NAME ORDER BY NAME) RN    
  FROM #tmp1 
)
SELECT a.name,a.price,b.price
FROM tmp a
INNER JOIN tmp1 b ON a.name=b.name AND a.RN=b.RN  AND a.PRICE <> b.PRICE