Question

I'm trying to get the unique record between two databases based on two criteria. The criteria is:

  1. If the data is found in database 1 (@SCCM in my example below), it is given preference
  2. 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
Was it helpful?

Solution

You can use partitions:

;WITH tbl as
(
    SELECT name0, resid, 2 as SMSDB FROM SMS
    UNION ALL
    SELECT name0, resid, 1 as SMSDB FROM SCCM
),
t as (
    SELECT *, 
           ROW_NUMBER()  
           over (partition By name0 order by SMSDB, resid desc ) 
           as rn
    FROM tbl
)
SELECT * FROM t
WHERE rn = 1

Results:

| NAME0 | RESID | SMSDB | RN |
------------------------------
|  TEST |   150 |     1 |  1 |
| TEST1 |   200 |     1 |  1 |
| TEST2 |   300 |     1 |  1 |
| TEST3 |  4000 |     2 |  1 

OTHER TIPS

The partition solution may in fact be better, but it hurts my brain. What about just excluding the values in SMS if they exist in SCCM?

SELECT MIN(SMSDB) as SMSDB, MAX(Resid), Name0 FROM
(
    SELECT name0, resid, 2 as SMSDB FROM @SMS SMS
    WHERE NOT EXISTS (SELECT * FROM @SCCM WHERE name0 = SMS.name0)
    UNION ALL
    SELECT name0, resid, 1 as SMSDB FROM @SCCM
) as tbl
GROUP BY NAME0

or even

SELECT 1 as SMSDB, MAX(resid), name0  FROM @SCCM
GROUP BY name0
UNION ALL
SELECT 2 as SMSDB, MAX(resid), name0 FROM @SMS SMS
WHERE NOT EXISTS (SELECT * FROM @SCCM WHERE name0 = SMS.name0)
GROUP BY name0
ORDER BY name0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top