combine 2 columns to one and pivot

ojm 61 Reputation points
2023-03-23T23:08:42.5566667+00:00

How do I combine 2 columns to 1 and pivot that table.

CREATE TABLE #Test 
(
	StudentName VARCHAR(20)
	,Class1Present INT
	,Class1Absent int
	,Class2Present INT
	,Class2Absent int
	,Class3Present INT
	,Class3Absent int

)

INSERT INTO #Test VALUES ('John', 0,0,3,2,3,4)
INSERT INTO #Test VALUES ('Mary', 5,1,4,3,4,4)
INSERT INTO #Test VALUES ('Tom', 0,6,7,0,3,3)
INSERT INTO #Test VALUES ('Susan', 1,5,3,4,4,3)

SELECT * FROM #Test

Suppose my table looks like this

User's image

and I want it to look like this

User's image

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,756 questions
0 comments No comments
{count} votes

Accepted answer
  1. CosmogHong-MSFT 23,321 Reputation points Microsoft Vendor
    2023-03-24T01:42:09.6533333+00:00

    Hi @ojm

    Please check this query:

    ;WITH CTE1 AS
    (
     SELECT StudentName
           ,CONCAT(Class1Present,'/',Class1Absent) AS Class1
    	   ,CONCAT(Class2Present,'/',Class2Absent) AS Class2
    	   ,CONCAT(Class3Present,'/',Class3Absent) AS Class3
     FROM #Test
    ),CTE2 AS
    (
     SELECT * FROM CTE1 
     UNPIVOT(Present_Absent FOR Class IN([Class1],[Class2],[Class3]))U
    )
    SELECT Class AS StudentName,[John],[Mary],[Tom],[Susan]
    FROM CTE2
    PIVOT(MAX(Present_Absent)FOR StudentName IN ([John],[Mary],[Tom],[Susan]))P
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Tiago Paumgartten 0 Reputation points
    2023-03-23T23:28:19.5366667+00:00

    Olá, a forma mais rápida é criar uma tabela virtual para cada CLASS, ou seja, 3 tabelas e por fim relacioná-las pelos estudantes. Mas é importante que todos os estudantes possuam valores em todos os campos, do contrário, seria preciso utilizar um LEFT e/ou RIGTH JOIN ou tratar os campos nulos com um NVL() talvez. Acredito que essa seria a forma mais simples e rápida, mas daria para utilizar algumas funções de PL/SQL para fazer isso de forma automática.

    0 comments No comments