使用减号操作时考虑重复的SQL

时间:2018-05-07 17:41:38

标签: sql sql-server

方案是使用下表,其中两列值以连字符

分隔

表1

Kavana-01
Sandhya-01
Sandhya-02

ExceptionTable

Kavana-01
Sandhya-01

可输出

Kavana-01
Sandhya-02

要求输出类似于outputttable = Table1 Minus ExceptionTable,考虑Table1中的唯一性。由于Kavana这个词是独一无二的,所以不应该考虑减号操作。

2 个答案:

答案 0 :(得分:1)

试试这个。假设col1和col2是第一列和第二列

    SELECT t.col1,t.col2,e1.col2 AS prio FROM 
(SELECT t1.col1,t1.col2, row_number() over (partition by t1.col1 order by CASE WHEN e1.col2 IS NULL THEN 0 ELSE 1 END) 
as OrderNumber
FROM Table1 t1
LEFT JOIN ExceptionTable e1 ON t1.col1=e1.col1 AND t1.col2=e1.col2) t
WHERE t.prio IS NULL OR t.OrderNumber=1

我的测试代码。我在这里使用临时表

CREATE TABLE #Table1 (
    col1 varchar(255),
    col2 varchar(255)
);


CREATE TABLE #ExceptionTable (
    col1 varchar(255),
    col2 varchar(255)
);

INSERT INTO #Table1 (col1,col2) values ('Kavana','01');
INSERT INTO #Table1 (col1,col2) values ('Sandhya','01');
INSERT INTO #Table1 (col1,col2) values ('Sandhya','02');
INSERT INTO #Table1 (col1,col2) values ('Mounil','01');
INSERT INTO #Table1 (col1,col2) values ('Mounil','02');

INSERT INTO #ExceptionTable (col1,col2) values ('Kavana','01');
INSERT INTO #ExceptionTable (col1,col2) values ('Sandhya','01');

--DROP TABLE #Table1
--DROP TABLE #ExceptionTable

SELECT * FROM #Table1
SELECT * FROM #ExceptionTable

SELECT t.col1,t.col2 FROM 
(SELECT t1.col1,t1.col2,e1.col2 AS prio, row_number() over (partition by t1.col1 order by CASE WHEN e1.col2 IS NULL THEN 0 ELSE 1 END) 
as OrderNumber
FROM #Table1 t1
LEFT JOIN #ExceptionTable e1 ON t1.col1=e1.col1 AND t1.col2=e1.col2) t
WHERE t.prio IS NULL OR t.OrderNumber=1

答案 1 :(得分:0)

SQL Server中的一个方法是except

select col1, col2
from table1
except
select col1, col2
from table2;