显示SQL Server 2014中ROW_NUMBER> 1的表中的所有记录

时间:2018-02-07 13:28:48

标签: sql sql-server row-number

我正在尝试显示RN > 1

表格中的所有记录

这是我遵循的代码和步骤

Create table #Data(id int,name Varchar(max))

Insert into #Data values
(1,'A'),
(2,'A'),
(3,'A'),
(4,'B'),
(5,'B'),
(1,'C')

Select *,ROW_NUMBER() over(partition by name order by id) as rn
into #temp
from #Data

--Fetching Subsequent records
select * from #Data
where name in 
(
   Select distinct name from #temp where rn>1
)

输出:

id  name
1   A
2   A
3   A
4   B
5   B

有人可以提出一个更好的方法,不包括中间临时表和子查询吗?

4 个答案:

答案 0 :(得分:1)

使用Cte,获取rownum

的记录
with cte as
(
Select *,ROW_NUMBER() over (partition by id order by name ) rn
from #Data)
select Id,Name from cte where rn<=1

答案 1 :(得分:0)

这对你有用吗?

$ tclsh
% package require rl_json
0.9.11
% set js {{"result":[{"geometry":{"bounds":{"lat":42,"long":24}}}]}}
{"result":[{"geometry":{"bounds":{"lat":42,"long":24}}}]}
% json get $js result
invalid command name "json"
% rl_json::json
Wrong # of arguments.  Must be "method ?arg ...?"
% namespace import rl_json::json
% json get $js result
{geometry {bounds {lat 42 long 24}}}
% json get $js result 0
geometry {bounds {lat 42 long 24}}
% json get $js result 0 geometry bounds lat
42

rn在子查询中,然后外部的where子句过滤掉。

答案 2 :(得分:0)

这是一个完整的工作示例,很像@B House,但是使用变量表而不是临时表,你确实说过rn&gt; 1

declare @example as table (
    exampleid int
,   name_ varchar(max)
);

insert into @example (exampleid, name_)
select 1, 'A' union all
select 2, 'A' union all
select 3, 'A' union all
select 4, 'B' union all
select 5, 'B' union all
select 1, 'C';

     ;with cte as (
        select row_number() over(partition by name_ order by exampleid) rn
             , *
          from @example
        )

        select *
          from cte
         where rn > 1

输出

rn  exampleid   name_
2   2           A
3   3           A
2   5           B

答案 3 :(得分:0)

如果我弄错了你想要计算每个name出现的次数。并选择计数&gt;的名称1.然后不需要使用row_number。检查此查询

select
    id, name
from (
    select
        *, cn = count(*) over (partition by name)
    from
        #Data
) t
where
    cn > 1

输出

id  name
--------
1   A
2   A
3   A
4   B
5   B