我创建了一个在每天结束时运行的存储过程,它将返回类(class)中每个学生的出勤百分比,结果集将显示学生之前的出勤百分比与新百分比的比较。但由于某种原因,结果存储在多行而不是一行中。下图将使您更好地理解问题。
两个表:
学生表
百分比表
我编写的用于将结果放入组合表中的代码:
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
这是此查询的结果集!
但这不是我想要的结果,下面显示了所需的结果集!
我认为 CASE
语句可以为我做到这一点,但显然我错了,有人可以给我一些关于我需要从这里去哪里的指示吗?
最佳答案
为什么不直接用子选择来进行选择呢?假设一名学生每天只能得到一个结果
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
关于sql - 结果以多行形式返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366975/