将SQL Pivot应用于表的最佳方法是什么?

时间:2017-03-08 17:43:43

标签: sql sql-server pivot

我正在尝试使用pivot功能但不确定如何将双周表中的字母替换为人名而不是查询结果。这是我的询问。

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|    |

非常感谢任何帮助。 谢谢!

1 个答案:

答案 0 :(得分:1)

我将忽略主题行中的问题,因为您的样本数据和所需的输出根本不需要PIVOT。

您可以通过使每列成为CASE表达式来获得所需的输出。在每个wk**列中,如果值不为空,则返回第一个名称的值,最后一个首字母(如果需要)和连接在一起的电话号码。