如何使用SQL创建追溯趋势

时间:2014-09-16 14:51:47

标签: sql sql-server database sql-server-2008 sql-server-2012

我有一些麻烦,只使用SQL

为下一个表创建一个追溯趋势

user_id | Date of Exam | Exam Name | Result -------------- +-----------------+--------------+------- 1 | 2013-01-01 6:00 | Geography | PASS 1 | 2013-01-02 6:00 | Math | FAIL 1 | 2013-01-03 6:00 | Geography | FAIL 1 | 2013-01-04 6:00 | Biology | FAIL 1 | 2013-01-04 7:00 | Biology | PASS 1 | 2013-01-04 6:00 | Math | FAIL 1 | 2013-01-04 7:00 | Math | PASS 2 | 2013-01-04 7:00 | Math | FAIL

我需要在特定日期范围内获得每天的通过率。例如,对于特定的一天X,我需要获得特定学生当天的最新可用结果(如果没有结果可用于他当前日期,我需要从前一天开始,如果前一天结果为空我需要从前一天开始,依此类推)。如果特定学生一天有多个结果,则应在计算中使用最新结果,忽略较旧结果。我需要获得特定日期每个考试组的通过百分比。结果表应如下所示

Exam Name | 2013-01-01 | 2013-01-02 | 2013-01-03 | 2013-01-04 ---------- +---------------+-- ------------+--------------+------------ Geography | 100% | 100% | 0% | 0% Math | NULL | 0% | 0% | 50% Biology | NULL | NULL | NULL | 100%

截至目前,我只设法每天返回多个表格。但我认为可以将它合并为一个表。这是获取特定日期最新结果的查询

select ExamName, COUNT(*) as TotalCount,
    sum(case when Result = 'PASS' then 1 else 0 end) PassCount 
    from (SELECT  
         UserID, 
         ExamName,            
         Result,
         DateOfExam,
         ROW_NUMBER() OVER (Partition BY UserID,  ExamName Order By DateOfExam DESC) AS RowNum
         From  dbo.ExamResults       
    where DateOfExam <= '2013-01-04 7:00'    
       ) T1
where T1.RowNum = 1
group by ExamName

SQLFiddle与一些DDL:http://sqlfiddle.com/#!6/6fde8/2/0

0 个答案:

没有答案