我有以下代码,但它显示了由于 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
能指教如何达到效果吗?谢谢。