你可以尝试这样的事情:
declare @medical table(id int, checks varchar(10))
declare @personal table(id int, checks varchar(10))
insert into @medical
select 1, 'abc1'
union
select 2, 'abc2'
insert into @personal
select 1, 'abc1'
union
select 2, 'abc22'
;WITH CTE AS (
select *, 'M' As Src from @medical
union
select *, 'P' As Src from @personal
)
SELECT checks, src, ROW_NUMBER() over (order by checks, id) new_id FROM CTE
在你的情况下:
SELECT checks, src, ROW_NUMBER() over (order by [checks], id) new_id
FROM
(
SELECT id, [Medical checks] Checks, 'M' as Src FROM MD_Master
UNION ALL
SELECT id, [Personal checks] Checks, 'P' as Src FROM CD_Personal
)