Search code examples
sqlsql-serverstringwhere-clauseunpivot

SQL pivot/Unpivot?


Really hoping someone can help me out here, I have a table structured as below:

The query to retrieve this data is:

SELECT

[Pattern Number]
,Sunday
,Monday
,Tuesday
,Wednesday
,Thursday
,Friday
,Saturday

FROM Access.Pattern_Details
WHERE [Pattern Number] = 4
+----------------+--------+--------+---------+-----------+----------+--------+----------+
| Pattern Number | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday |
+----------------+--------+--------+---------+-----------+----------+--------+----------+
|              4 |      0 |      1 |       1 |         1 |        1 |      1 |        0 |
+----------------+--------+--------+---------+-----------+----------+--------+----------+

That I'd like to get looking like this:

+----------------+------------+-----------+
| Pattern Number | WorkingDay |    Day    |
+----------------+------------+-----------+
|              4 |          0 | Sunday    |
|              4 |          1 | Monday    |
|              4 |          1 | Tuesday   |
|              4 |          1 | Wednesday |
|              4 |          1 | Thursday  |
|              4 |          1 | Friday    |
|              4 |          0 | Saturday  |
+----------------+------------+-----------+

I've tried PIVOT/UNPIVOT which feels like the right direction to go in, but am really struggling with how to get the result :(


Solution

  • In SQL Server, I would recommend cross apply and values():

    select pd.[Pattern Number], x.*
    from Access.Pattern_Details pd
    cross apply (values 
        ('Sunday',    Sunday), 
        ('Monday',    Monday),
        ('Tuesday',   Tuesday),
        ('Wednesday', Wednesday),
        ('Thursday',  Thursday),
        ('Friday',    Friday),
        ('Saturday',  Saturday)
    ) x(day, workingDay)
    where pd.[Pattern Number] = 4