2015-03-30 129 views

回答

1

所有類似的行我的回答,我認爲你有一個ID獨特價值和排除。

表創建:

CREATE TABLE #TRXN (ID INT IDENTITY(1, 1) 
        ,ACCT_NUM INT 
        ,TRAN_MEMO INT 
        ,AMOUNT INT 
        ,[DATE] DATE 
        ,LRN INT 
) 

樣本數據插入

INSERT INTO #TRXN VALUES (1, 2, 2, '1 jan 2000', 2) 
         ,(2, 2, 2, '2 jan 2000', 2) 
         ,(1, 2, 2, '1 jan 2000', 2) 
         ,(1, 2, 2, '1 jan 2000', 3) 

有相同LRN但其它列中的至少一個具有不同的值

;WITH C AS(
    SELECT ROW_NUMBER() OVER (PARTITION BY ACCT_NUM, TRAN_MEMO, AMOUNT, [DATE], LRN ORDER BY ACCT_NUM, TRAN_MEMO, AMOUNT, [DATE], LRN) AS Rn 
      ,ID, ACCT_NUM, TRAN_MEMO, AMOUNT, [DATE], LRN 
    FROM #TRXN WHERE LRN IN(
    SELECT LRN FROM #TRXN GROUP BY LRN HAVING COUNT(ID) > 1) 
) 
SELECT ID, ACCT_NUM, TRAN_MEMO, AMOUNT, [DATE], LRN 
FROM C WHERE Rn = 1 

輸出:

ID ACCT_NUM TRAN_MEMO AMOUNT DATE  LRN 
--------------------------------------------- 
1 1  2   2  2000-01-01 2 
2 2  2   2  2000-01-02 2 
+0

令人驚歎!謝謝! – 2015-03-31 01:28:30

0

爲什麼簡單地說,使用GROUP BY:

SELECT COUNT(1) AS numberOfGroupedRows,ID,ACCT_NUM,TRAN_MEMO,AMOUNT,DATE,LRN 
FROM TRNX GROUP BY ID,ACCT_NUM,TRAN_MEMO,AMOUNT,DATE,LRN 
自組

通過它將組一行

+0

我想編寫一個查詢來提取具有相同LRN但至少有一列具有不同值的記錄。 – 2015-03-30 21:53:09

+0

爲我提供簡單的表格數據 – 2015-03-30 22:02:47