SQL Server數據庫中如何合并表格數據
SQL Server數據庫是如何合并表格數據的呢?其實SQL Server數據庫合并表格數據是利用ROW_NUMBER來實現的,本文我們通過一個例子來介紹如何合并表格數據。我使用的數據庫版本是SQL Server 2005,表格的原始數據如下:
這個一個學習和測試的記錄,Type是類型(0學習,1測試)。一天中可能會學習多次,也可能會測試多次,學習次數和測試次數可能不一樣。
想要的到得是,按日期列出當天學習和測試的記錄。
類似這樣的結果:(圖中兩行數據一樣,是兩種語言表示)
主要的SQL語句如下:
- select A.Date,A.MID,A.Contents1,B.Contents2,B.Passed from
- (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents1 from History where Type=0 ) A
- left join
- (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents2,Passed from History where Type=1 ) B
- on A.Date=B.Date and A.MID=B.MID
- union
- select B.Date,B.MID, A.Contents1,B.Contents2,B.Passed from
- (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents1 from History where Type=0 ) A
- right join
- (select ROW_NUMBER() over(partition by Date order by Date) as MID,Date,Contents as Contents2,Passed from History where Type=1) B
- on A.Date=B.Date and A.MID=B.MID
結果如下:
至此,表格的數據已經合并完畢了。
關于SQL Server數據庫合并表格數據的知識就介紹到這里,如果您想了解更多關于SQL Server數據庫的知識,可以看一下這里的文章:http://database.51cto.com/sqlserver/,相信一定會帶給您收獲的!
【編輯推薦】