I’m trying to get the unique record between two databases based on two criteria. The criteria is:
- If the data is found in database 1 (@SCCM in my example below), it
is given preference - Grab the MAX resource id within the selected database
Here is an example, which is half working. The database preference is working, but the maximum resource id WITHIN that database isn’t. Right now it’s selecting the max between both @SMS and @SCCM
DECLARE @SMS TABLE (
name0 varchar(100),
resid int
)
DECLARE @SCCM TABLE (
name0 varchar(100),
resid int
)
INSERT INTO @SMS
SELECT 'TEST', 1000 UNION
SELECT 'TEST', 1500 UNION
SELECT 'TEST1', 2000 UNION
SELECT 'TEST2', 3000 UNION
SELECT 'TEST3', 4000
INSERT INTO @SCCM
SELECT 'TEST', 100 UNION
SELECT 'TEST', 150 UNION
SELECT 'TEST1', 200 UNION
SELECT 'TEST2', 300
SELECT MIN(SMSDB) as SMSDB, MAX(Resid), Name0 FROM
(
SELECT name0, resid, 2 as SMSDB FROM @SMS
UNION ALL
SELECT name0, resid, 1 as SMSDB FROM @SCCM
) as tbl
GROUP BY NAME0
Expected results:
SMSDB | Resid | Name0
----------------------
1 | 150 | TEST
1 | 200 | TEST1
1 | 300 | TEST2
2 | 4000 | TEST3
You can use partitions:
Results: