2012-09-24 91 views
1

我試圖根據兩個標準獲取兩個數據庫之間的唯一記錄。的標準是:TSQL UNION獲取獨特價值

  1. 如果數據在數據庫1實測值(@SCCM下面的示例所示),它 被給予優先
  2. 抓鬥選定的數據庫內的MAX資源ID

這是一個例子,這是一半工作。數據庫首選項正在工作,但該數據庫中的最大資源ID不在。現在它選擇既@SMS和@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 

預期結果之間的最大:

SMSDB | Resid | Name0 
---------------------- 
1  | 150 | TEST 
1  | 200 | TEST1 
1  | 300 | TEST2 
2  | 4000 | TEST3 

回答

1

您可以使用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 
0

T他的分區解決方案實際上可能更好,但它傷害了我的大腦。如果在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 

甚至

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