2011-09-06 133 views
1

我仍在努力將數據完全按照我想要的方式提取出來,而且幾乎就是這樣 - 最後一個問題。數據透視表內日期比較

這裏是我的代碼:

 DECLARE @QA1 TABLE (SID varchar(7), FormID varchar(max), DateExam date, Present varchar(3)) 

     INSERT INTO @QA1 VALUES(1, 'Form1', '20110101', 'Yes') 
     INSERT INTO @QA1 VALUES(2, 'Form1', '20110201', 'Yes') 
     INSERT INTO @QA1 VALUES(3, 'Form1', '20110301', 'Yes') 
     INSERT INTO @QA1 VALUES(4, 'Form1', '20110401', 'Yes') 
     INSERT INTO @QA1 VALUES(5, 'Form1', '20110122', 'Yes') 
     INSERT INTO @QA1 VALUES(1, 'Form2', '20110222', 'Yes') 
     INSERT INTO @QA1 VALUES(2, 'Form2', '20110322', 'Yes') 
     INSERT INTO @QA1 VALUES(3, 'Form2', '20110422', 'Yes') 
     INSERT INTO @QA1 VALUES(1, 'Form3', '20110128', 'Yes') 
     INSERT INTO @QA1 VALUES(1, 'Form4', '20110228', 'Yes') 
     INSERT INTO @QA1 VALUES(5, 'Form5', '20110328', 'Yes') 
     INSERT INTO @QA1 VALUES(5, 'Form6', '20111228', 'Yes') 
     INSERT INTO @QA1 VALUES(4, 'Form2', '20111228', 'Yes') 

     SELECT SID, 
     ISNULL(MIN(CASE FormID WHEN 'Form1' THEN Present END), '') AS 'First Form', 
     ISNULL(MIN(CASE FormID WHEN 'Form2' THEN isnull(CONVERT(varchar(12),DateExam,107),'') END), '') as 'Date F2 Exam', 
     ISNULL(MIN(CASE FormID WHEN 'Form2' THEN Present END), '') AS 'Second Form', 
     ISNULL(MIN(CASE FormID WHEN 'Form4' THEN Present END), '') AS 'Fourth Form', 
     ISNULL(MIN(CASE FormID WHEN 'Form5' THEN Present END), '') AS 'Fifth Form', 
     ISNULL(MIN(CASE FormID WHEN 'Form6' THEN Present END), '') AS 'Sixth Form', 

     ISNULL(MIN(CASE FormID WHEN 'Form3' THEN Present END), 

     MIN(CASE FormID WHEN 'Form2' THEN isnull(CONVERT(varchar(12),DateExam,107),'') END) 

    ) AS 'Third Form' 


     FROM @QA1 


     GROUP BY SID 
     ORDER BY SID 

這給了我這樣的輸出:

SID First Form  Date F2 Exam  Second Form Fourth Form Fifth Form Sixth Form Third Form 
1  Yes   Feb 22, 2011  Yes   Yes         Yes 
2  Yes   Mar 22, 2011  Yes            Mar 
3  Yes   Apr 22, 2011  Yes            Apr 
4  Yes   Dec 28, 2011  Yes            Dec 
5  Yes           Yes   Yes      NULL 

這是非常接近我想,但我真正想要的第三種形式列是要麼一個是,超過到期或空白(''),逾期定義爲今天超過Form2的DateExam超過34天。

最後一個CASE語句成功從Form2中抽取DateExam,但現在我需要檢查它是否過期。我是否需要另一個CASE或嵌套的if-then-else來添加日期?我知道要添加我的34天,我需要DATEADD(第34天,DateExam),我將檢查它與GETDATE(),但在CASE語句中if-then-else語句應該是什麼形式?

感謝

回答

0

嘗試改變Third Form的定義是這樣的:

COALESCE(
    MIN(CASE FormID WHEN 'Form3' THEN Present END), 
    CASE 
    WHEN DATEDIFF(D, MIN(CASE FormID WHEN 'Form2' THEN DateExam END), GETDATE()) > 34 
     THEN 'Overdue' 
    ELSE '' 
    END 
) AS 'Third Form'