选择不同的行

时间:2014-04-23 16:15:27

标签: sql sql-server

有了这个请求:

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 个答案:

答案 0 :(得分: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