xicano66
xicano66

Reputation: 5

What is the best way to apply SQL Pivot to a table?

I'm trying to use the pivot function but not sure how to replace the Letters in the bi-weekly table to a persons name instead of the query result. Here is my query.

SELECT a.OCD, a.[f_name],a.[l_name],a.[ads_phone], b.wk1m, b.wk1t, b.wk1w, b.wk1r, b.wk1f, b.wk2m, b.wk2t, b.wk2w, b.wk2r, b.wk2f
FROM [dbo].[tbl_teleworkers] as a
inner join [dbo].[tbl_scheduled] as b ON  a.pin = b.pin
where ocd = '022'

here is my result:
OCD|f_name|l_name|ads_phone|wk1m|wk1t|wk1w|wk1r|wk1f|wk2m|wk2t|wk2w|wk2r|wk2f
022|John  |smith |111-1111 |M   |    |    | R  |    |    |    |    |    |
022|Jane  |smith |222-2222 |    |    |    |    |    |    |    |  W |    |
022|Joe   |smith |333-3333 |M   |    |    |    |  F |    |    |    |    |
022|Jim   |smith |444-4444 |    | T  |    |    |    | M  |    |    |    |
022|Jill  |smith |555-5555 |M   |    | W  |    |    |    |    |    |  R |

Here is what I'm looking to get: So instead of the letters of the week. I'm trying to display the person's name and phone number.
wk1m |wk1t|wk1w|wk1r |wk1f|wk2m|wk2t|wk2w  |wk2r|wk2f
John |    |    |John |    |    |    |      |    |
phone|    |    |phone|    |    |    |      |    |
     |    |    |     |    |    |    |Jane S|    |
     |    |    |     |    |    |    |phone |    |
Joe  |    |
phone|    |

Any help would be greatly appreciated. Thanks!

Upvotes: 0

Views: 43

Answers (1)

Tab Alleman
Tab Alleman

Reputation: 31785

I'm going to ignore the question in your subject line because your sample data and desired output do not require a PIVOT at all.

You can get your desired output by making each column a CASE expression. In each wk** column, if the value is not empty, return the value of the first name, last initial (if desired) and phone number concatenated together.

Upvotes: 1

Related Questions