PHP中通过sqlsrv调用存储过程——成绩排名去除重复字段的数据行

时间:2023-03-08 20:39:53

培训考试项目中,需要实现考试成绩排名:排名参考项为分数(score降序)、参加日期(attendtime升序)、第几次参加考试(frequency升序);并且,每个用户只保留一条数据(pid)。

考试结果存储表格如下:

PHP中通过sqlsrv调用存储过程——成绩排名去除重复字段的数据行

期望得到的结果为:

PHP中通过sqlsrv调用存储过程——成绩排名去除重复字段的数据行

解决思路:

  • 去重:
    • 考虑到dintinct针对单个字段比较有效,结合其他字段使用时,效果不理想;
    • 嵌套语句先进行排名,再去除重复的pid数据行;尝试半天没写出来;请教同学,由他给出下一条方案
    • 使用临时表,分语句查询;先排名为temp1表,后在temp1表中删除分数小的重复的pid行,再删除考试次数大的重复的pid行,添加rankid字段结合其他字段生成新的temp2临时表;此方法经测试可行,创建为存储过程代码如下:
 Create  PROCEDURE [dbo].[myZhenxin]
@examid int
AS
BEGIN
if object_id('tempdb..#temp1') is not null
Begin
drop table #temp1
End if object_id('tempdb..#temp2') is not null
Begin
drop table #temp2
End -- Insert statements for procedure here
select id,frequency,attendtime, examid,score,pid into #temp1 from ExamResult where examid=@examid order by score desc,attendtime delete #temp1 where id in(select a.id from #temp1 a, #temp1 b where a.pid = b.pid and a.score<b.score) delete #temp1 where id in(select a.id from #temp1 a, #temp1 b where a.pid = b.pid and a.frequency>b.frequency ) select IDENTITY(int,,) rankid, examid,pid,score,frequency,attendtime into #temp2 from #temp1 select * from #temp2
END

在sql server中,调用存储过程的语句为:

exec myZhenxin ''

在php中使用sqlsrv调用存储过程:

 if ( ($stmt = sqlsrv_query($conn, $tsql)) )
{
// now, iterate through all the statements in
// stored proc or script $tsql:
do
{
// process the result of the iteration
if ( sqlsrv_num_fields($stmt) > 0 )
{
// we have a result set
while ( ($row=sqlsrv_fetch_array($stmt)) )
{
// do something with $row
}
}
else
{
// we have something else
$rowsAffected = sqlsrv_rows_affected($stmt);
}
} while ( ($next = sqlsrv_next_result($stmt)) ) ; if ( $next === NULL )
{
// it worked
}
else
{
// it didn't work, check sqlsrv_errors()
} sqlsrv_free_stmt($stmt);
}