2012-10-18 59 views
1

我有一個問題,我需要顯示學生的科目名稱(前英文,科學....)作爲列和每個主題下他們各自的標記。我查詢數據庫並將這些值作爲數據集中的行而不是列。我應該如何查詢數據庫?在SQL Server中檢索數據列明智

我的查詢結果

student name | marks | Subectname 
------------------------------------ 
raghuram  78   english 
raghuram  34   physics 
raghuram  76   chemistry 

................    ...   .......... 

在報告中要求的結果

studentname | english | Maths | physics | ...... 
---------------------------------------------------- 
raghuram  78  66  32 

這裏是我的查詢

SELECT 
    st.FirstName + ' ' + st.LastName as StudentName, 
    s.Subject_Name, se.Mark 
FROM 
    dbo.FEE_STUDENT_EXAM se 
INNER JOIN 
    dbo.FEE_STUDENT_GRADE sg ON sg.Student_ID=se.Student_ID 
INNER JOIN 
    FEE_STUDENT st ON st.Student_ID=sg.Student_ID 
INNER JOIN 
    dbo.EMP_SUBJECT s ON s.SubjectID=se.Subject_ID 
WHERE 
    sg.Grade_ID = @GradeId 
    AND sg.Division_ID = @DivId 
    AND se.Subject_ID IN (SELECT d.SubjectId 
          FROM dbo.FEE_STUDENT_EXAM_SCHEDULED d 
          INNER JOIN dbo.FEE_STUDENT_EXAM_SCHEDULEH h ON h.ExamScheduleID = d.ExamScheduleID 
          WHERE h.Grade_Id = @GradeId AND h.Division_ID = @DivId 
          AND YEAR(CAST(d.TestDate AS DATETIME)) = @Year 
          AND MONTH(CAST(d.TestDate AS DATETIME)) = @Month) 

回答

0

添加GROUP BY到您的查詢,max(case...)您需要的每個主題:

Select st.FirstName+' '+st.LastName as 
      StudentName, 

      max(case when s.Subject_Name = 'english' then se.Mark else 0 end) as english,  
      max(case when s.Subject_Name = 'Maths' then se.Mark else 0 end) as Maths, 
      max(case when s.Subject_Name = 'physics' then se.Mark else 0 end) as physics, 
......... 

    from dbo.FEE_STUDENT_EXAM se 
        inner join dbo.FEE_STUDENT_GRADE sg on sg.Student_ID=se.Student_ID 
        inner join FEE_STUDENT st on st.Student_ID=sg.Student_ID 
        inner join dbo.EMP_SUBJECT s on s.SubjectID=se.Subject_ID 
        where [email protected] and [email protected] and 
        se.Subject_ID in(Select d.SubjectId from dbo.FEE_STUDENT_EXAM_SCHEDULED d inner join 
        dbo.FEE_STUDENT_EXAM_SCHEDULEH h on h.ExamScheduleID=d.ExamScheduleID where 
        [email protected] and [email protected] and year(cast (d.TestDate as datetime))[email protected] 
        and month(cast (d.TestDate as datetime))[email protected]) 

       Group by se.Student_ID 
+0

這裏我們不知道所有科目是什麼present.It可能隨着更高的類別.. – ksg

+0

您還可以使用[PIVOT](http://msdn.microsoft.com/en-us/library/ms177410(v = sql.105).aspx),但它也需要一個固定的列列表。 – valex

+0

或者您也可以動態地進行查詢。 [在這裏你可以找到一個例子。](http://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server-2005/) – valex