2012-04-05 67 views
1

我想从下一行选择下一行

因此,如果表就像

field1 field2 field3 

text1 text3 order1 
text2 text4 order1 

我想做到这一点串联当前行两个文本字段与同场:

if (field3.current_row = field3.next_row) 
    SELECT field1 + getNextRow(field1) as "Concatenated Field" FROM table 

这可能吗?

+5

你需要一些方法来识别*当前记录*和下一个记录*。如果您无法定义查找这些记录的标准,则无法回答此问题。 – Yuck 2012-04-05 15:39:26

+0

您可以使用row_number和三角形连接来完成此操作。请参阅以下链接http://www.sqlservercentral.com/Forums/Topic483631-338-1.aspx – 2012-04-05 15:40:26

+0

表中是否有ID列或只是field1和field2? – 2012-04-05 15:58:09

回答

2

你可以做一些与此类似:

create table #temp 
(
    field1 varchar(50), 
    field2 varchar(50) 
) 

insert into #temp values ('text1', 'text3') 
insert into #temp values ('text2', 'text4') 

;with cte as 
(
    select *, row_number()over(order by field1) as rownum 
    from #temp 
) 
SELECT * 
FROM 
(
    select c1.field1 + ' ' + (SELECT field1 FROM cte c2 WHERE c2.rownum = c1.rownum + 1) as ConcField 
    from cte c1 
) c 
where c.concfield is not null 

drop table #temp 
3

如果你已经是SQL Server的上,你可以做到以下几点:

SELECT field1 + lead(field1) over (order by field1) as "Concatenated Field" 
from table