Row_Number()返回重复的行

时间:2015-10-16 11:47:42

标签: sql sql-server-2008 stored-procedures rownum

这是我的查询,

SELECT top 100
    UPPER(COALESCE(A.DESCR,C.FULL_NAME_ND)) AS DESCR,
    COALESCE(A.STATE, (SELECT TOP 1 STATENAME 
                       FROM M_STATEMASTER 
                       WHERE COUNTRYCODE = B.CODE)) AS STATENAME,
    COALESCE(A.STATECD, (SELECT TOP 1 CODE 
                         FROM M_STATEMASTER 
                         WHERE COUNTRYCODE = B.CODE)) AS STATECD,
    COALESCE(A.COUNTRYCD, B.CODE) AS COUNTRYCODE
FROM 
    M_CITY A
JOIN 
    M_COUNTRYMASTER B ON A.COUNTRYCD = B.CODE
JOIN 
    [GEODATASOURCE-CITIES-FREE] C ON  B.ALPHA2CODE = C.CC_FIPS
WHERE 
    EXISTS (SELECT 1 
            FROM [GEODATASOURCE-CITIES-FREE] Z 
            WHERE B.ALPHA2CODE=Z.CC_FIPS) 
ORDER BY 
    A.CODE

完美正常工作,但是当我试图获得Row_number() over(order by a.code)我多次获得重复列时。

e.g

SELECT top 100
    UPPER(COALESCE(A.DESCR,C.FULL_NAME_ND)) AS DESCR,
    COALESCE(A.STATE, (SELECT TOP 1 STATENAME 
                       FROM M_STATEMASTER 
                       WHERE COUNTRYCODE = B.CODE)) AS STATENAME,
    COALESCE(A.STATECD, (SELECT TOP 1 CODE 
                         FROM M_STATEMASTER 
                         WHERE COUNTRYCODE = B.CODE)) AS STATECD,
    COALESCE(A.COUNTRYCD, B.CODE) AS COUNTRYCODE
    ROW_NUMBER() OVER(ORDER BY A.CODE) AS RN -- i made a change here
FROM 
    M_CITY A
JOIN 
    M_COUNTRYMASTER B ON A.COUNTRYCD = B.CODE
JOIN 
    [GEODATASOURCE-CITIES-FREE] C ON  B.ALPHA2CODE = C.CC_FIPS
WHERE 
    EXISTS (SELECT 1 
            FROM [GEODATASOURCE-CITIES-FREE] Z 
            WHERE B.ALPHA2CODE=Z.CC_FIPS) 
ORDER BY 
    A.CODE
WHERE 
    EXISTS (SELECT 1 
            FROM [GEODATASOURCE-CITIES-FREE] Z 
            WHERE B.ALPHA2CODE = Z.CC_FIPS)

另一次尝试,当我使用ROW_NUMBER() OVER(ORDER BY newid()) AS RN时,它会占用登录时间来执行。

请记住:CODE是表格M_CITY的Pk,而[GEODATASOURCE-CITIES-FREE]表格中没有关键字。

另一件事:关于JOIN(内连接),Join返回匹配的Rows,右边???

例如:

table 1 with 20 rows,
table2 with 30 rows ,
table 3 with 30 rows

如果我在某个键上加入这3个表,那么获得最大行的可能性是20,我是对的吗?

1 个答案:

答案 0 :(得分:1)

您的第一个查询无效。它似乎只是。原因是您使用的TOP没有ORDER BY,因此会返回100行的任意组。

添加ROW_NUMBER()时,查询计划会发生变化。 。 。并且结果集的顺序也会改变。我建议你修复原始查询以使用稳定的排序。