2015-02-06 186 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