I am a beginner with SQL Server and am struggling to figure out how to update my query so that it displays my data correctly.
I checked out Combine similar column data from two rows into one row and attempted to do a group by on QueryID but am not sure how to apply this when I'm needing it to group by the number at the end of the text and by the id#. I have also looked at numerous posts on pivot/unpivot to perform multiple pivots but am struggling to apply it.
My current query and sample results are below. What I'm wanting to see is where the QueryID ends in the same number AND the employee ID is equal, the Date/Level/Reason all return to the same row rather than 3 separate rows. I appreciate any guidance.
With DisciplineTable as
(
Select HrEmployees.Number,
HrEmployees.FirstName + ' ' + HrEmployees.LastName as Name,
HrEmployeeQueries.QueryID,
HrEmployeeQueries.Query,
HrEmployeeQueries.Response
From HrEmployeeQueries
Left Join HrEmployees on HrEmployees.EmployeeID = HrEmployeeQueries.EmployeeID
Where QueryID Like 'DIS%')
Select *
From DisciplineTable
Pivot(Max(Response) for Query in ([DATE:],[LEVEL:],[REASON:])) as DisciplinaryAction
Where QueryID Like 'DIS%'
Order by Name
My results look something like this:
+-----+----------+---------+----------+---------+-------------+
| # | Name | QueryID | DATE: | LEVEL: | REASON: |
+-----+----------+---------+----------+---------+-------------+
| 123 | John Doe | Date2 | 10/16/14 | Null | Null |
| 123 | John Doe | Level2 | Null | Serious | Null |
| 123 | John Doe | Reason2 | Null | Null | Attendance |
| 123 | John Doe | Date3 | 12/13/14 | Null | Null |
| 123 | John Doe | Level3 | Null | Major | Null |
| 123 | John Doe | Reason3 | Null | Null | Performance |
+-----+----------+---------+----------+---------+-------------+
and I'm trying to get them to look like this. The Action
column should be populated with the numeric value at the end of QueryID
, which could go from 1-10. The text at the start of QueryID
will always be Date
, Reason
or Level
:
+-----+----------+--------+----------+---------+-------------+
| # | Name | Action | DATE: | LEVEL: | REASON: |
+-----+----------+--------+----------+---------+-------------+
| 123 | John Doe | 2 | 10/16/14 | Serious | Attendance |
| 123 | John Doe | 3 | 12/13/14 | Major | Performance |
+-----+----------+--------+----------+---------+-------------+