SQL Server數(shù)據(jù)庫中如何合并表格數(shù)據(jù)
作者:朱靜程
本文我們主要介紹了SQL Server數(shù)據(jù)庫利用ROW_NUMBER來合并表格數(shù)據(jù)的一個例子,希望能夠?qū)δ兴鶐椭?/div>
SQL Server數(shù)據(jù)庫是如何合并表格數(shù)據(jù)的呢?其實SQL Server數(shù)據(jù)庫合并表格數(shù)據(jù)是利用ROW_NUMBER來實現(xiàn)的,本文我們通過一個例子來介紹如何合并表格數(shù)據(jù)。我使用的數(shù)據(jù)庫版本是SQL Server 2005,表格的原始數(shù)據(jù)如下:
這個一個學習和測試的記錄,Type是類型(0學習,1測試)。一天中可能會學習多次,也可能會測試多次,學習次數(shù)和測試次數(shù)可能不一樣。
想要的到得是,按日期列出當天學習和測試的記錄。
類似這樣的結(jié)果:(圖中兩行數(shù)據(jù)一樣,是兩種語言表示)
主要的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
結(jié)果如下:
至此,表格的數(shù)據(jù)已經(jīng)合并完畢了。
關(guān)于SQL Server數(shù)據(jù)庫合并表格數(shù)據(jù)的知識就介紹到這里,如果您想了解更多關(guān)于SQL Server數(shù)據(jù)庫的知識,可以看一下這里的文章:http://database.51cto.com/sqlserver/,相信一定會帶給您收獲的!
【編輯推薦】
責任編輯:趙鵬
來源:
博客園


相關(guān)推薦




