简体   繁体   中英

How to make Single Column into Rows in Sql Server 2008 R2?

Hi i am in confusing state to run an Sql Query, My table looks like this

在此处输入图片说明

from the above image there are two columns. First column consists of Register No of the student. Second Column Consists his/Her Exam Results. P States he is passed in the Certain Subject.In the report i want result set like the below. If the Result consists any number he is failed in the following subject.

  • 1--->English 2--->Sanskrit 3--->Maths 4--->Science 5--->Social

i want the result should be like this. Can any body help me in this. i am not getting any idea.

在此处输入图片说明

Try Below Query

SELECT RegisterNo,'English' AS Subject ,
     CASE WHEN SUBSTRING(Result+ SPACE(5),1,1) = 'P' THEN 'Pass'
          WHEN ISNUMERIC(SUBSTRING(Result+ SPACE(5),1,1)) = 1 THEN 'Fail'
          ELSE 'Invalid' END AS Result
FROM table1
UNION ALL 
SELECT RegisterNo,'Sanskrit' AS Subject ,
     CASE WHEN SUBSTRING(Result+ SPACE(5),3,1) = 'P' THEN 'Pass'
          WHEN ISNUMERIC(SUBSTRING(Result+ SPACE(5),3,1)) = 1 THEN 'Fail'
          ELSE 'Invalid' END AS Result
FROM table1
UNION ALL 
SELECT RegisterNo,'Maths' AS Subject ,
       CASE WHEN SUBSTRING(Result+ SPACE(5),5,1) = 'P' THEN 'Pass'
            WHEN ISNUMERIC(SUBSTRING(Result+ SPACE(5),5,1)) = 1 THEN 'Fail'
            ELSE 'Invalid' END AS Result
FROM table1
UNION ALL 
SELECT RegisterNo,'Science' AS Subject ,
       CASE WHEN SUBSTRING(Result+ SPACE(5),7,1) = 'P' THEN 'Pass'
            WHEN ISNUMERIC(SUBSTRING(Result+ SPACE(5),7,1)) = 1 THEN 'Fail'
            ELSE 'Invalid' END AS Result
FROM table1
UNION ALL 
SELECT RegisterNo,'Social' AS Subject ,
       CASE WHEN SUBSTRING(Result+ SPACE(5),9,1) = 'P' THEN 'Pass'
            WHEN ISNUMERIC(SUBSTRING(Result+ SPACE(5),9,1)) = 1 THEN 'Fail'
            ELSE 'Invalid' END AS Result
FROM table1
ORDER BY RegisterNo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM