显示重复值

时间:2017-12-06 03:47:41

标签: sql-server duplicates

我下面有一张桌子(#tempX)。

BoxNumber | Location 
----------|----------
ABC123    |Nowra
ABC123    |Sydney
KLM222    |Melbourne
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
PQR888    |Brisbane

我需要找到副本并显示它们。

BoxNumber | Location 
----------|----------
ABC123    |Nowra
ABC123    |Sydney
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan

我使用了下面的查询(您可以将其复制并粘贴到您的SQL服务器上)但是它并没有提供我正在寻找的内容。它给了我一张空白表。

If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (box varchar(max) ,location varchar(max))

insert into #tempX (box,location)
values ('ABC123','Nowra'),('ABC123','Sydney'),('KLM222', 'Melbourne'),('XYZ444','Karatha'),('XYZ444','Mirabooka'),('XYZ444','Logan'),('PQR888','Brisbane')

--select * from #tempx

select distinct Box, Location, count(*) from #tempX
group by Box, Location
having count(*) > 1

我正在使用SQL Server 2012.谢谢大家。

3 个答案:

答案 0 :(得分:0)

它无效,因为您正在尝试查找Box AND 位置的重复值。

    url = "{% url 'add-member' 0 'change-team' %}";
    url = url.replace(0, id).replace('change-team', input);

或:

Select a.* from 
    #tempX a join 
            (   
            select Box from #tempX
            group by Box
            having count(Box) > 1
            ) b on a.box = b.box
order by a.box, a.Location 

答案 1 :(得分:0)

试试这个

    create table #tmp (BoxNumber VARCHAR(25),Location  VARCHAR(25))

    INSERT INTO #tmp VALUES('ABC123','Nowra')
    INSERT INTO #tmp VALUES('ABC123','Sydney')
    INSERT INTO #tmp VALUES('KLM222','Melbourne')
    INSERT INTO #tmp VALUES('XYZ444','Karatha')
    INSERT INTO #tmp VALUES('XYZ444','Mirabooka')
    INSERT INTO #tmp VALUES('XYZ444','Logan')
    INSERT INTO #tmp VALUES('PQR888','Brisbane')



    ;with cte
    AS
    (
        SELECT ROW_NUMBER()OVER(Partition by BoxNumber order by BoxNumber) as [rank],* From #tmp
    )


    SELECT DISTINCT t.* from #tmp t
    JOIN cte c on t.BoxNumber=c.BoxNumber and c.[rank]>1

    /*

        -- OR (BELOW Query also returns the same result)

        SELECT * from #tmp
        WHERE BoxNumber in 
        (   
                SELECT  BoxNumber from cte where [rank]>1
        )

    */

    Drop table #tmp

答案 2 :(得分:0)

你可以这样做:

   select *
      from #tempX 
     where  Box in   
           ( select Box
               from #tempX 
              group by Box
             having count(*) > 1 )