PHP中通過sqlsrv調用存儲過程——成績排名去除重復字段的數據行


培訓考試項目中,需要實現考試成績排名:排名參考項為分數(score降序)、參加日期(attendtime升序)、第幾次參加考試(frequency升序);並且,每個用戶只保留一條數據(pid)。

考試結果存儲表格如下:

期望得到的結果為:

 

解決思路:

  • 去重:
    • 考慮到dintinct針對單個字段比較有效,結合其他字段使用時,效果不理想;
    • 嵌套語句先進行排名,再去除重復的pid數據行;嘗試半天沒寫出來;請教同學,由他給出下一條方案
    • 使用臨時表,分語句查詢;先排名為temp1表,后在temp1表中刪除分數小的重復的pid行,再刪除考試次數大的重復的pid行,添加rankid字段結合其他字段生成新的temp2臨時表;此方法經測試可行,創建為存儲過程代碼如下:

 

 1 Create  PROCEDURE [dbo].[myZhenxin] 
 2     @examid int
 3 AS
 4 BEGIN
 5     if object_id('tempdb..#temp1') is not null
 6      Begin
 7     drop table #temp1
 8     End
 9     
10     if object_id('tempdb..#temp2') is not null
11      Begin
12     drop table #temp2
13     End
14 
15     -- Insert statements for procedure here
16     select id,frequency,attendtime, examid,score,pid into #temp1 from ExamResult where examid=@examid  order by score desc,attendtime         
17      
18     delete #temp1 where id in(select a.id from #temp1 a,  #temp1 b where a.pid = b.pid and a.score<b.score)
19       
20     delete #temp1 where id in(select a.id from #temp1 a,  #temp1 b where a.pid = b.pid and a.frequency>b.frequency )
21      
22     select IDENTITY(int,1,1) rankid, examid,pid,score,frequency,attendtime into #temp2 from #temp1
23      
24     select * from #temp2
25 END

 

在sql server中,調用存儲過程的語句為:

exec myZhenxin '11'

在php中使用sqlsrv調用存儲過程:

 1 if ( ($stmt = sqlsrv_query($conn, $tsql)) )
 2 {
 3     // now, iterate through all the statements in 
 4     // stored proc or script $tsql:
 5     do
 6     {
 7         // process the result of the iteration
 8         if ( sqlsrv_num_fields($stmt) > 0 )
 9         {
10              // we have a result set
11              while ( ($row=sqlsrv_fetch_array($stmt)) )
12              {
13                    // do something with $row
14              }
15         }
16         else
17         {
18              // we have something else
19              $rowsAffected = sqlsrv_rows_affected($stmt);
20         }
21     } while ( ($next = sqlsrv_next_result($stmt)) ) ;
22 
23     if ( $next === NULL )
24     {
25         // it worked
26     }
27     else
28     {
29         // it didn't work, check sqlsrv_errors()
30     }
31     
32     sqlsrv_free_stmt($stmt);
33 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM