2014-04-23 96 views
0

有了這個請求:SELECT DISTINCT線

SELECT * 
FROM 
    (SELECT DISTINCT 
     ROW_NUMBER() OVER (ORDER BY test2.A1 ASC) AS line, 
     test1.A1, test1.A2, test2.A1 
    FROM 
     TB_TEST1 test1 
JOIN 
     TB_TEST2 test2 ON test2.A3 != 'test' AND test2.A4 = test1.A4 
    WHERE 
     test1.A3 != 'test') AS sub 
WHERE 
    line BETWEEN 1 AND 50 

我得到:

1 a 1 AAA 
2 a 1 BBB 
3 b 7 AAA 
4 b 7 BBB 
5 c 11 AAA 
6 c 12 BBB 

但我想只有在第二列和第三列是唯一的行:

1 c 11 AAA 
2 c 12 BBB 

哪有我這樣做?

+1

使用'集團BY'。 –

+2

tb_test1和tb_test2的外觀如何?也許我可以爲你寫一個更簡單的查詢?你有什麼數據,你想得到什麼數據? –

回答

1

嘗試移動ROWNUMBER子查詢外:

SELECT 
    ROW_NUMBER() OVER (ORDER BY sub.TEST1_A1 ASC) AS line 
, TEST1_A1 
, TEST1_A2 
, TEST2_A1 
FROM (
    SELECT DISTINCT test1.A1 AS TEST1_A1, test1.A2 AS TEST1_A2, test2.A1 AS TEST2_A1 
    FROM TB_TEST1 test1 
    JOIN TB_TEST2 test2 ON test2.A3!='test' AND test2.A4 = test1.A4 
    WHERE test1.A3!='test') as sub 
WHERE line BETWEEN 1 AND 50