结果以多行返回

时间:2015-02-06 13:34:40

标签: sql sql-server-2008

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

两个表:

学生表

enter image description here

百分比表

enter image description here

我编写的代码将结果放入组合表中:

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声明对我来说会这样做,但显然我错了,有人可以告诉我一些关于我需要离开的地方吗?

2 个答案:

答案 0 :(得分: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 :(得分: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