2

In mssql, imagine I have a table with the following data...

id   name   monday   tuesday   wednesday   thursday   friday
1    mark    null    chores      null       gym        swim
2    steve   gym     null        class      hockey     null
3    mike    chores  gym         null       null       null

I would like to have a sql statement, that would return the id, name and day column where the value is not null, for example...

id    name    day        value
1     mark    tuesday    chores
1     mark    thursday   gym
1     mark    friday     swim
2     steve   monday     gym
2     steve   wednesday  class
2     steve   thursday   hockey
2     mike    monday     chores
2     mike    tuesday    gym

Thank you.

2
  • 1
    You should create table to save week days, and then do a relation between people -- days Commented Jul 22, 2016 at 12:37
  • select * from yourtable where value is null Commented Jul 22, 2016 at 12:37

2 Answers 2

3

One method is union all, but I prefer outer apply:

select t.id, t.name, dayname, value
from t outer apply
     (values ('monday', monday),
             ('tuesday', tuesday),
             ('wednesday', wednesday),
             ('thursday', thursday),
             ('friday', friday),
             ('saturday', saturday),
             ('sunday', sunday)
     ) v(dayname, value)
where value is not null;
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this solution first, and it worked exactly as I wanted. Thank you.
2

try

select * from yourTable 
unpivot
(
day1 for value in (monday,   tuesday,   wednesday,   thursday,friday) 
) upt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.