Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>DDL:</strong></p> <pre><code>DECLARE @temp TABLE ( Reg_No INT , Student_Name VARCHAR(20) , Subject1 INT , Subject2 INT , Subject3 INT , Subject4 INT , Total INT ) INSERT INTO @temp (Reg_No, Student_Name, Subject1, Subject2, Subject3, Subject4, Total) VALUES (101, 'Kevin', 85, 94, 78, 90, 347), (102, 'Andy ', 75, 88, 91, 78, 332) </code></pre> <p><strong>Query #1 - ROW_NUMBER:</strong></p> <pre><code>SELECT Reg_No = CASE WHEN rn = 1 THEN t.Reg_No END , Student_Name = CASE WHEN rn = 1 THEN t.Student_Name END , t.[Subject] , Total = CASE WHEN rn = 1 THEN t.Total END FROM ( SELECT Reg_No , Student_Name , [Subject] , Total , rn = ROW_NUMBER() OVER (PARTITION BY Reg_No ORDER BY 1/0) FROM @temp UNPIVOT ( [Subject] FOR tt IN (Subject1, Subject2, Subject3, Subject4) ) unpvt ) t </code></pre> <p><strong>Query #2 - OUTER APPLY:</strong></p> <pre><code>SELECT t.* FROM @temp OUTER APPLY ( VALUES (Reg_No, Student_Name, Subject1, Total), (NULL, NULL, Subject2, NULL), (NULL, NULL, Subject3, NULL), (NULL, NULL, Subject4, NULL) ) t(Reg_No, Student_Name, [Subject], Total) </code></pre> <p><strong>Query Plan:</strong></p> <p><img src="https://i.stack.imgur.com/7Kay7.png" alt="tt"></p> <p><strong>Query Cost:</strong></p> <p><img src="https://i.stack.imgur.com/ygJP7.png" alt="tt2"></p> <p><strong>Output:</strong></p> <pre><code>Reg_No Student_Name Subject Total ----------- -------------------- ----------- ----------- 101 Kevin 85 347 NULL NULL 94 NULL NULL NULL 78 NULL NULL NULL 90 NULL 102 Andy 75 332 NULL NULL 88 NULL NULL NULL 91 NULL NULL NULL 78 NULL </code></pre> <p><strong>PS:</strong> In your case query with <code>OUTER APPLY</code> is faster than <code>ROW_NUMBER</code> solution.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload