1

我有以下 sql 查询:

select @table1 as DataState, *  from
(select * from importedcsvclients 
except 
select * from tblClients) x
union all
select @table2 as DataState, *  from
(select * from tblClients 
except select *  
from importedcsvclients) x

上面的代码工作正常,但是,如果 table1 和 table2 包含相似的数据,则两条记录都会显示。

谁能帮助我使查询工作为:

获取 table1 和 table2 的结果,但如果 table1 中不存在相同的名称,则仅显示 table2 数据。

谢谢。

信息:

table1
ID   Name
1    TestA
2    TestB    
3    TestC
4    TestD

table2
ID   Name
1    TestE
2    TestF    
3    TestG
4    TestD

Results:
Name     DataState
TestA    table1
TestB    table1
TestC    table1
TestD    table1
TestE    table2
TestF    table2
TestG    table2
4

3 回答 3

3

使用起来非常诱人,EXCEPT但正如您所发现的那样,从稍微复杂的任何事情中获得正确的结果并不总是那么简单。这是使用 CTE 后的结果的尝试:

DECLARE @table1 TABLE(ID INT, Name VARCHAR(32));    
INSERT @table1 VALUES (1,'TestA'), (2,'TestB'), (3,'TestC'), (4,'TestD');

DECLARE @table2 TABLE(ID INT, Name VARCHAR(32));
INSERT @table2 VALUES (1,'TestE'), (2,'TestF'), (3,'TestG'), (4,'TestD');

;WITH x AS 
(
  SELECT m, Name, rn = ROW_NUMBER() OVER (PARTITION BY Name ORDER BY m)
  FROM 
  (
    SELECT m = 'table1', Name FROM @table1
    UNION ALL 
    SELECT m = 'table2', Name FROM @table2
  ) AS y
)
SELECT Name, DataState = m
  FROM x 
  WHERE rn = 1
  ORDER BY Name;

结果:

Name        DataState
---------   ---------
TestA       table1
TestB       table1
TestC       table1
TestD       table1
TestE       table2
TestF       table2
TestG       table2
于 2012-04-26T03:04:53.253 回答
0

在(伪)关系代数中:

table1 UNION ( table2 NOT MATCH table1 )

在 TSQL 中(添加DataState):

SELECT ID, Name, 
       'table1' AS DataState
  FROM table1
UNION
SELECT ID, Name,
       'table2' AS DataState
  FROM table2
 WHERE Name NOT IN ( SELECT Name FROM table1 );

包括您的样本数据测试数据:

WITH table1 
     AS
     (
      SELECT * 
        FROM (
              VALUES (1, 'TestA'),
                     (2, 'TestB'),    
                     (3, 'TestC'),
                     (4, 'TestD')
             ) AS T (ID, Name)
     ),
     table2
     AS
     (
      SELECT * 
        FROM (
              VALUES (1, 'TestE'),
                     (2, 'TestF'),    
                     (3, 'TestG'),
                     (4, 'TestD')
             ) AS T (ID, Name)
     )
SELECT ID, Name, 
       'table1' AS DataState
  FROM table1
UNION
SELECT ID, Name,
       'table2' AS DataState
  FROM table2
 WHERE Name NOT IN ( SELECT Name FROM table1 );
于 2012-04-26T07:45:21.737 回答
0

我现在用下面的。感谢所有帮助。

DECLARE @sql VARCHAR(8000)
SET @sql = 'SELECT ''' + @table1 + ''' AS DataState, * FROM
(SELECT ' + @columnlist + ' FROM ' + @table1 + '
    EXCEPT
SELECT ' + @columnlist + ' FROM ' + @table2 + ') x
    UNION
SELECT ''' + @table2 + ''' AS DataState, * from
    (SELECT ' + @columnlist + ' FROM ' + @table2 + '
        INTERSECT
    SELECT ' + @columnlist + ' FROM ' + @table1 +') x'

EXEC(@sql) 
于 2012-04-27T16:06:51.107 回答