我正在使用SQL Server 2008.我有一个不包含任何唯一列的表;如何从中获取备用行?
SQL Server表:
+-----+--------+
| id | name |
|-----+--------|
| 1 | abc |
| 2 | pqr |
| 2 | pqr |
| 3 | xyz |
| 4 | lmn |
| 5 | efg |
| 5 | efg |
+-----+--------+
由于我们至少提出了一个有关问题的工作建议,我已尝试过以下代码;当从大量数据中获取时,这不是那么合适的技术。
试验:
create table #tmp
(
id int, name varchar(10), srNo int
)
insert into #tmp
select
id, name,
ROW_NUMBER() OVER (ORDER BY id) % 2 as srNo --,alternate rows
from
Employee
select *
from #tmp
where srNo = 1 --or srNo = 0
上面的查询给出了替代行,即第1,第3,第5 OR 第2,第4,第6等。
请在没有#tmp
的情况下以正确方式 帮助我实现目标!
谢谢!
答案 0 :(得分:2)
您可以将select语句用作内嵌视图。你不需要#tmp表。
select t.id, name
from (select id, name, ROW_NUMBER() over (order by id) as srNo from Employee) t
where (t.srNo % 2) = 1
答案 1 :(得分:1)
- 从表中获取ALTERNATE记录(EVEN NUMBERED)
Select * from TableName where ColumnName % 2 = 0
对于Eg:从HumanResources.Employee中选择*,其中BusinessEntityID%2 = 0
- 从表中获取ALTERNATE记录(ODD NUMBERED)
Select * from TableName where ColumnName % 2 = 1
对于例如:从HumanResources.Employee中选择*,其中BusinessEntityID%2 = 1
答案 2 :(得分:0)
使用 having
子句也可以实现同样的效果;但它增加了group by
任务:
SELECT id, name
FROM (SELECT id, name, ROW_NUMBER()over(order by id) AS srNo FROM Employee) x
GROUP BY srNo, id, name
HAVING (srNo % 2) = 0
答案 3 :(得分:0)
您可以仅将select语句用作嵌入式视图。您不需要#tblCities表。
select tbl1.CityID,tbl1.CityName from (select ROW_NUMBER() over(order by CityID asc) as row_no,CityID,CityName from tblCities) as tbl1 where tbl1.row_no%2=1
答案 4 :(得分:0)
declare @t table
(
id int,
name nvarchar(20)
)
insert into @t
Select 1, 'abc'
union all
Select 2, 'pqr'
union all
Select 2, 'pqr'
union all
Select 3, 'xyz'
union all
Select 4, 'lmn'
union all
Select 5, 'efg'
union all
Select 2, 'efg'
Select * from(
Select *, row_number() over(order by id) as rnum from @t ) t where rnum % 2 <> 0
答案 5 :(得分:0)
我以学生为表名。
这是我的答案->
> SELECT id from (SELECT rowno, id from student) where mod(rowno,2)=0
> SELECT id from (SELECT rowno, id from student) where mod(rowno,2)=1