SQL Server数据库中如何合并表格数据

数据库 SQL Server
本文我们主要介绍了SQL Server数据库利用ROW_NUMBER来合并表格数据的一个例子,希望能够对您有所帮助。

SQL Server数据库是如何合并表格数据的呢?其实SQL Server数据库合并表格数据是利用ROW_NUMBER来实现的,本文我们通过一个例子来介绍如何合并表格数据。我使用的数据库版本是SQL Server 2005,表格的原始数据如下:

SQL Server数据库中如何合并表格数据

这个一个学习和测试的记录,Type是类型(0学习,1测试)。一天中可能会学习多次,也可能会测试多次,学习次数和测试次数可能不一样。

想要的到得是,按日期列出当天学习和测试的记录。

类似这样的结果:(图中两行数据一样,是两种语言表示)

SQL Server数据库中如何合并表格数据

主要的SQL语句如下:

  1. select A.Date,A.MID,A.Contents1,B.Contents2,B.Passed from  
  2.  
  3. (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents1 from History where Type=0 ) A  
  4.  
  5. left join   
  6.  
  7. (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents2,Passed from History where Type=1 ) B  
  8.  
  9. on A.Date=B.Date and A.MID=B.MID  
  10.  
  11. union  
  12.  
  13. select  B.Date,B.MID, A.Contents1,B.Contents2,B.Passed from  
  14.  
  15. (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents1 from History where Type=0 ) A  
  16.  
  17. right join   
  18.  
  19. (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents2,Passed from History where Type=1) B  
  20.  
  21. on A.Date=B.Date and A.MID=B.MID 

结果如下:

SQL Server数据库中如何合并表格数据

至此,表格的数据已经合并完毕了。

关于SQL Server数据库合并表格数据的知识就介绍到这里,如果您想了解更多关于SQL Server数据库的知识,可以看一下这里的文章:http://database.51cto.com/sqlserver/,相信一定会带给您收获的!

【编辑推荐】

  1. SQL Server 2008如何创建定期自动备份任务
  2. SQL Server数据库如何更改SA密码和默认端口号
  3. SQL Server数据库随机抽取数据效率优化总结篇
  4. 一个SQL Server数据库文件批量重命名的代码示例
  5. SQL SERVER数据挖掘之如何实现Web路径流挖掘
责任编辑:赵鹏 来源: 博客园
相关推荐

2010-07-15 17:28:50

SQL Server

2011-03-11 13:26:23

SQL Server数导入数据

2010-07-01 15:02:29

SQL Server数

2015-10-30 14:00:33

adosybaseodbc

2010-07-06 13:22:13

SQL Server

2021-05-17 06:57:34

SQLServer数据库

2010-07-08 11:05:14

SQL Server数

2011-08-04 15:55:25

SQL Server数

2011-03-02 17:41:28

2011-03-18 09:48:32

2011-03-28 15:28:03

SQL Server 数据库

2009-04-22 09:42:07

SQL Server监视镜像

2010-07-08 15:55:25

SQL Server

2011-08-25 16:13:31

SQL Server批量替换数据

2009-06-03 10:51:59

连接SQL数据库Adobe Dream

2011-08-09 12:27:16

SQL Server tempdb

2021-05-08 14:07:26

SQLServer数据库

2023-09-05 00:06:45

2018-03-06 09:30:58

2011-04-06 17:30:41

SQL ServerSQL
点赞
收藏

51CTO技术栈公众号