c# - 表合并到自身

标签 c# sql tsql

我创建了一个表“Test”

create table test
(
  id int identity(1,1) not null,
  correlation int,
  data varchar(max)
)

下面是表格的数据

insert into test(correlation,data) values(1,'x0')
insert into test(correlation,data) values(1,'x1')
insert into test(correlation,data) values(2,'z1')
insert into test(correlation,data) values(2,'z2')
insert into test(correlation,data) values(3,'a')
insert into test(correlation,data) values(4,'b')
insert into test(correlation,data) values(5,'c')

我需要在网页上显示数据并将表连接到自身 关联并做分页

例如,如果我有两个具有相同相关性的记录 (1),我需要 将两行显示为一行,数据为当前数据和先前数据。 在下面的示例中,当前数据将为 x1,之前的数据将为 x0。

之前

 Correlation  Data
    1         x0    
    1         x1    

之后

Correlation     Previous Data   Current Data
1                  xo             x1

如果关联只有一行,则结果中的先前关联将为空。

目前我在 Linq 中进行了分页并且它正在工作但我担心将来它会花费 性能问题。

sameone 可以帮助我使用 SQL 吗。

这个问题还有其他好的解决方案吗

最佳答案

;with C as
(
  select correlation,
         data,
         row_number() over(partition by correlation order by id desc) as rn
  from @test
  where SomeColumn > 10 -- Where clause goes here (if possible)
)  
select C1.correlation,
       C2.data as [Previous Data],
       C1.data as [Current Data]
from C as C1
  left outer join C as C2 
    on C1.correlation = C2.correlation and
       C2.rn = 2
where C1.rn = 1

结果:

correlation Previous Data Current Data
----------- ------------- ------------
1           x0            x1
2           z1            z2
3           NULL          a
4           NULL          b
5           NULL          c

关于c# - 表合并到自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8257507/

相关文章:

c# - 实现 IEqualityComparer 会修改相等性测试结果吗?

c# - 使用 lambda 和事件在 C# 中使用技巧

c# - Request.GetResponseAsync() 在后台任务中不起作用,没有引发异常

sql - 提取最后一次出现字符之前的字符串

tsql - 使用 T-SQL 创建表时,为什么最后一个字段后面的逗号不重要?

c# - ASP.NET MVC 2 显示()

php - 查询未插入数据库

mysql - 使用 MySQL 计算字符串中字符的出现次数

html - 使用 SQL FOR XML 创建 HTML 表

sql-server - 在 sql 查询中替换第一个 FROM