문제

Table strucuture

In the image above, i have shown table structure i use to store result of student. However I need to select data in such a manner such that depending on particular FEID(examination ID), I get marks obtained and subID of single student in single row. Something like below:

 FEID  SubID1  MarksObtained  SubID2  MarksObtained  SubID3  MarksObtained  StdID  
 2     1       0              2       0              3       0              50         
 2     1       45             2       45             3       45             51

Result Column wont affect outcome as for a particular stdID and FEID it remains same for no matter how many SubID are there. Basically I am storing each subject marks in single row and subjects are can be any number( more than 3 as in this case) , which is not known before hand. But for each I create one row to enter its marks

I tried sytax below .

  DECLARE @cols nvarchar(MAX);
    --get the list of subids from the table
    SELECT @cols =  SubjectName from tbSubjects where SubID IN(select distinct SubID from tbFinalMarks);

    Declare @sql nvarchar(MAX) = 'SELECT StdId, FEID, ' + @cols + 'FROM 
    (
    SELECT * FROM tbFinalMarks
    )t
    PIVOT
    (
      MAX(MarksObtained) FOR SubId IN (' + @cols + ')

)p';
도움이 되었습니까?

해결책

Something like this will do it. It will also dynamically add new columns for new sub ids without you needing to worry about it.

    DECLARE @cols nvarchar(MAX);
    --get the list of subids from the table
    SELECT @cols = COALESCE(@cols + ',', '') + '[' + CAST(SubId AS nvarchar) + ']' FROM (SELECT DISTINCT SubId FROM table);

    Declare @sql nvarchar(MAX) = 'SELECT StdId, FEID, ' + @cols + 'FROM 
    (
    SELECT * FROM table
    )t
    PIVOT
    (
      MAX(MarksObtained) FOR SubId IN (' + @cols + ')

)p';

EXECUTE sp_executesql @sql;

다른 팁

Although you can use pivot, I think the explicit aggregation approach is easier to construct:

select feid,
       1 as SubId_1,
       max(case when SubId = 1 then MarksObtained end) as MarksObtained_1,
       2 as SubId_2,
       max(case when SubId = 2 then MarksObtained end) as MarksObtained_2,
       3 as SubId_3,
       max(case when SubId = 3 then MarksObtained end) as MarksObtained_3,
       stdid
from table t
group by feid, stdid;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top