2015-02-06 106 views
2

我创建了一个在每天结束时运行的存储过程,它将返回每个学生在一个班级中的出勤率,结果集将显示学生先前出勤率与他们的比较新百分比。但由于某些原因,结果被存储在多行而不是一行中。下面的图表会让你更好地理解问题。多行返回的结果

两个表:

学生表

enter image description here

率表格

enter image description here

我写拿到RESU代码将它转换为组合表格:

select 
StudentTb.StudentId, 
StudentTb.Forename, 
StudentTb.Surname, 
CONVERT(VARCHAR(10),DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE())-1, 0),103) as [Previous Reading Date] 
case studentTb.Date 
when DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE())-1, 0) then PercentageTb.Percentage 
End 
'Previous Percentage' 
CONVERT(VARCHAR,DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),103) as [Present Reading Date] 
case studentTb.Date 
when DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE())-1, 0) then PercentageTb.Percentage 
End 
'Current Percentage' 
from studentTb inner join 
        PercentageTb on studentTb.StudentID = PercentageTb.StudentID 

这是这个查询的结果集!

enter image description here

然而,这不是我想要的结果的方式看,下面显示了所需的结果集!

enter image description here

enter image description here

我以为CASE声明会做对我来说,但显然我错了,可能有人请给我,我需要从这里去一些指示?完成你想要的应该工作什么

+0

错误地插入了期望的结果集! – user3538102 2015-02-06 13:35:15

+0

只是我还是有很多语法错误...? – Nightmaresux 2015-02-06 13:51:07

+0

你的加入是问题所在。你需要更多的逻辑来分解它。连接为每个学生匹配2行(即2 * 2 = 4) – ricky89 2015-02-06 13:52:09

回答

1

一种方法是使用max()聚合函数扁平化的结果是这样的:

select 
    s.StudentID, 
    s.Forename, 
    s.Surname, 
    max(case when p.date = CONVERT(VARCHAR,DATEADD(DAY, DATEDIFF(DAY, 1, GETDATE()), 0),103) then p.date end) prev_date, 
    max(case when p.date = CONVERT(VARCHAR,DATEADD(DAY, DATEDIFF(DAY, 1, GETDATE()), 0),103) then p.percentage end) prev_perc, 
    max(case when p.date = CONVERT(VARCHAR,DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),103) then p.date end) curr_date, 
    max(case when p.date = CONVERT(VARCHAR,DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),103) then p.percentage end) curr_perc 
from studentTb s 
inner join percentageTb p on s.StudentID = p.StudentID 
group by s.StudentID, s.Forename, s.Surname 

Sample SQL Fiddle

另一种选择是加入percentageTb表两次(一次为当前日期,一次为前一天),请参见this example

1

为什么不只是做一个选择与子选择?假设学生每天只能得到一个结果

DECLARE @CurrentDate DATE 
DECLARE @PreviousDate DATE 
SET @CurrentDate = 
SET @PreviousDate = 


SELECT 
    StudentTb.StudentId AS [ID], 
    StudentTb.Forename AS [Forename], 
    StudentTb.Surname AS [Surname], 
    (SELECT Percentage from PercentageTb where StudentID = S.studentID and Date = @PreviousDate) AS [PreviousPercentage] 
    (SELECT Percentage from PercentageTb where StudentID = S.studentID and Date = @CurrentDate) AS [CurrentPercentage] 
from studentTb AS S