MS SQL根据两个表检索某些结果

时间:2012-04-26 07:10:50

标签: sql sql-server

我有以下代码,但由于UNION显示所有记录:

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

exec(@sql)

我需要的结果如下:

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    table2 

可以建议如何实现结果吗? 感谢。

1 个答案:

答案 0 :(得分:0)

左连接应该完成这项工作,我想:

SELECT
  t1.Name,
  DataState = COALESCE(t2.DataState, 'table1')
FROM table1 t1
  LEFT JOIN (
    SELECT
      Name,
      DataState = 'table2'
    FROM table2
  ) t2 ON t1.Name = t2.Name

或者联系应该在ID列,我不确定。无论如何,这至少应该给你一个想法。