Question

I have a SQL table which stores the Status and Location of employees

empID            date         status     location
---------------------------------------------------------
001            01.01.2014        1         1
001            02.01.2014        2         1
001            04.01.2014        1         3
....
055            01.01.2014        3         3
055            02.01.2014        4         2

Now I want to create a list with the employee id and days 1 to 31 as columns and a concatenation of the Status and Location as the value. If I take max() of the status, it works, however, the location information is missing. If I try to do

SELECT *
FROM (SELECT (empId), left(datename(dd,[Date]),2)as [day_date], [Status] as status, [Location] as location, [Status] + '|' + [Location] as val FROM [dbo].[table]

 WHERE [date] BETWEEN '2014-01-01' AND '2014-01-30') as s

PIVOT (MAX(val) FOR [day_date] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])

)AS p

order by empID

it fails because I can't use max() against a concatenated string.

My goal is:

empID            01    02    03    04  ....     30    31
---------------------------------------------------------
001              1|1   2|1   null  1|3         null  null
055              3|4   4|2   null  null        null  null
Was it helpful?

Solution

Cast [Status] and [Location] to a varchar performing the concatenation. I have arbitrarily chosen 3 as the length of the varchar but that may vary depending on what your maximum possible [Status] and [Location] are.

Also, remove the [Status] and [Location] columns from the inner query.

SELECT *
FROM (
    SELECT 
        empId, 
        left(datename(dd,[Date]),2)as [day_date],
        cast([Status] AS varchar(3)) + '|' + cast([Location] as varchar(3)) as val 
    FROM [dbo].[table]
WHERE [date] BETWEEN '2014-01-01' AND '2014-01-30') as s
PIVOT (MAX(val) FOR [day_date] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
)AS p
order by empID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top