jeudi 11 février 2016

SQL merging rows with dynamic column headings

I am trying to populate a Gridview to have checkboxes enabled per student, but depending to certain values from this query:

@SelectedDate is provided via a TextBox as a date only

SELECT  v1.StudentID,
        v1.StudentPreferredName + ' ' + v1.StudentFamilyName AS StudentName,
        bcs.CheckStatusName,
        rce.DateSubmitted,
        rcp.RollCallPeriod
FROM tblBoardingRollCallEntries AS rce
     INNER JOIN vwBoardingTenants AS v1
        ON v1.StudentID = rce.StudentID
       AND v1.[Year] = YEAR(@SelectedDate)
     INNER JOIN tblBoardingCheckStatus AS bcs
        ON bcs.CheckStatusID = rce.CheckStatusID
       AND bcs.StatusActive = 1
     INNER JOIN tblBoardingRollCallPeriods AS rcp
         ON rcp.RollCallPeriodID = rce.RollCallPeriodID
        AND rcp.PeriodYear = YEAR(@SelectedDate)
        AND @SelectedDate BETWEEN rcp.PeriodStart AND rcp.PeriodEnd
        AND rcp.RowStatus = 1
WHERE dbo.fnDateOnly(rce.DateSubmitted) = dbo.fnDateOnly(@SelectedDate)

My gridview:

Shows the following:

enter image description here

The data:

enter image description here

I want to be able to basically condense the rows in the GridView to be one student per row and the checkboxes ticked according to RollCallPeriod text.

I am playing with SQL pivots, to get the data to be as close as possible to what I am after so as to avoid code-behind, etc. However, I cannot get this to work.

select StudentID, [1],[10],[2],[3],[4],[5],[6],[7],[8],[9]
      from
      (
        select StudentID, RollCallID, CheckStatusID
        from tblBoardingRollCallEntries
        unpivot
        (
          value for name in ([RollCallID],[StudentID],[CheckStatusID],[DateSubmitted],[StaffID])
        ) unpiv
      ) src
      pivot
      (
        sum(RollCallPeriodID)
        for RollCallPeriodID in ([1],[10],[2],[3],[4],[5],[6],[7],[8],[9])
      ) piv

I receive the following error:

Lookup Error - SQL Server Database Error: The type of column "StudentID" conflicts with the type of other columns specified in the UNPIVOT list.

Any other ideas?

Thanks

Aucun commentaire:

Enregistrer un commentaire