| 首先我們建立如下的表: sc(成績表) stuid clsid????????????????????????????????????????????? scroe???????????????????????????????????????????????? ----- -------- ----------------------------------------------------- 0101? 1????????????????????????????????????????????????? 75.0 0102? 1????????????????????????????????????????????????? 70.0 0103? 1????????????????????????????????????????????????? 90.0 0101? 2????????????????????????????????????????????????? 89.0 0102? 2????????????????????????????????????????????????? 80.0 0103? 2????????????????????????????????????????????????? 99.0 0101? 3????????????????????????????????????????????????? 89.0 0102? 3????????????????????????????????????????????????? 79.0 0103? 3????????????????????????????????????????????????? 67.0 其中stuid表示學生編號,clsid表示課程編號,scroe表示成績 stu(學生表) stuid?????? stuname??????????????????????????????????????????? ----------- -------------------------------------------------- 101???????? 張三 102???????? 李四 103???????? 王五 cls(課程表) clsid?????? name?????????????????????????????????????????????? ----------- -------------------------------------------------- 1?????????? 語文 2?????????? 數學 3?????????? 英語 接下來就是關鍵了,其實也不算好復雜,就是用到了動態sql declare @sql nvarchar(4000),@sql1 nvarchar(4000) select @sql='',@sql1='' select @sql=@sql+',['+name+']=sum(case clsid when '''+clsid+''' then scroe else 0 end)', ?????? @sql1=@sql1+',['+name+'名次]=(select sum(1) from # where ['+name+']>=a.['+name+'])'?????? from(select distinct b.clsid,c.name from sc as b inner join cls as c on c.clsid=b.clsid) as a order by clsid exec('select stuid 學號'+@sql+',總成績=sum(scroe) ,平均分=Convert(dec(5,1),avg(scroe)),總名次=(select sum(1) from(select stuid,aa=sum(scroe) from sc group by stuid) aa where sum(a.scroe)<=aa) into # from sc as a group by stuid select b.stuname as 姓名,a.*'+@sql1+' from # as a inner join stu as b on a.學號=b.stuid') 以下就是結果: 姓名??? 學號??? 語文??? 數學??? 英語??? 總成績? 平均分 總名次 語文名次 數學名次 英語名次??? ---------------------------------------------------- -------------------------------------- 張三???? 0101??? 75.0??? 89.0????? 89.0???? 253.0????? 84.3???????? 2???????????? 2??????????????? 2?????????????? 1 李四?????0102??? 70.0??? 80.0????? 79.0???? 229.0????? 76.3???????? 3???????????? 3?????????????? ?3?????????????? 2 王五?????0103??? 90.0??? 99.0????? 67.0???? 256.0????? 85.3???????? 1???????????? 1?????????????? ?1?????????????? 3 這就是交叉表的用法,對于報表統計很有用處,我們可以依此類推寫出功能更強大的查詢。 |