SQL Server數(shù)據(jù)庫(kù)中如何合并表格數(shù)據(jù)
作者:朱靜程
本文我們主要介紹了SQL Server數(shù)據(jù)庫(kù)利用ROW_NUMBER來合并表格數(shù)據(jù)的一個(gè)例子,希望能夠?qū)δ兴鶐椭?/div>
SQL Server數(shù)據(jù)庫(kù)是如何合并表格數(shù)據(jù)的呢?其實(shí)SQL Server數(shù)據(jù)庫(kù)合并表格數(shù)據(jù)是利用ROW_NUMBER來實(shí)現(xiàn)的,本文我們通過一個(gè)例子來介紹如何合并表格數(shù)據(jù)。我使用的數(shù)據(jù)庫(kù)版本是SQL Server 2005,表格的原始數(shù)據(jù)如下:

這個(gè)一個(gè)學(xué)習(xí)和測(cè)試的記錄,Type是類型(0學(xué)習(xí),1測(cè)試)。一天中可能會(huì)學(xué)習(xí)多次,也可能會(huì)測(cè)試多次,學(xué)習(xí)次數(shù)和測(cè)試次數(shù)可能不一樣。
想要的到得是,按日期列出當(dāng)天學(xué)習(xí)和測(cè)試的記錄。
類似這樣的結(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ù)庫(kù)合并表格數(shù)據(jù)的知識(shí)就介紹到這里,如果您想了解更多關(guān)于SQL Server數(shù)據(jù)庫(kù)的知識(shí),可以看一下這里的文章:http://database.51cto.com/sqlserver/,相信一定會(huì)帶給您收獲的!
【編輯推薦】
責(zé)任編輯:趙鵬
來源:
博客園

相關(guān)推薦


















