Share via

Combining columns

RoyB09 306 Reputation points
2021-02-11T14:38:03.333+00:00

Hello

I've got the query below with the columns StudentID, StartDate, ExamDate and ResultDate. I want to return the 2nd row set StudentID and xDate.

I could do it using union queries, but is there a cleaner way. I've also tried pivoting, but it doesn't give me the required results.

Thanks in advance Roy

66928-image.png

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Nasreen Akter 10,896 Reputation points Volunteer Moderator
2021-02-11T15:03:11.867+00:00

Hi @RoyB09 ,

Please try the following:

Create Table #std (StudentID INT,StartDate Datetime, ExamDate Datetime, ResultDate Datetime);    
GO    
INSERT INTO #std VALUES (101,'01/01/2019','01/06/2019','01/07/2019');    
INSERT INTO #std VALUES (102,'01/01/2020','01/06/2020','01/07/2020');    
INSERT INTO #std VALUES (103,'01/01/2021','01/06/2021','01/07/2021');   
  
SELECT StudentID, DatesFrom, FORMAT(Dates, 'yyyy/MM/dd') AS Dates  
FROM  
(SELECT StudentID, StartDate, ExamDate, ResultDate FROM #std) as p	  
UNPIVOT( Dates FOR DatesFrom IN (StartDate, ExamDate, ResultDate)) AS unstd  

Thanks!

----------

If the above response is helpful, please "accept as answer" and up-vote it. Thanks!

Was this answer helpful?

2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Michael Taylor 61,221 Reputation points
    2021-02-11T15:06:23.25+00:00

    What do you mean by you want to return the second resultset? Other than the student ID what do they have in common? The second resultset includes 3 values for each student whereas the first only has a single value. Do you want to combine these together such that your second result is returned but merged with the data for the first? In that case a JOIN is what you want.

    SELECT a.StudentId, a.StartDate, a.ExamDate, a.ResultDate, b.xDate
    FROM table1 a LEFT JOIN table2 b ON a.StudentId = b.StudentId
    

    I'm using a left join here so all the rows in table1 will be included and any matching rows in table2 will be merged in.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.