将 SQL 枢轴应用于 table 的最佳方法是什么?
What is the best way to apply SQL Pivot to a table?
我正在尝试使用 pivot 函数,但不确定如何将双周刊 table 中的 Letters 替换为人名而不是查询结果。这是我的查询。
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| |
如有任何帮助,我们将不胜感激。
谢谢!
我将忽略您主题行中的问题,因为您的示例数据和所需的输出根本不需要 PIVOT。
您可以通过使每一列成为 CASE 表达式来获得所需的输出。在每个 wk**
列中,如果值不为空,return 名字、姓氏首字母(如果需要)和 phone 数字连接在一起的值。
我正在尝试使用 pivot 函数,但不确定如何将双周刊 table 中的 Letters 替换为人名而不是查询结果。这是我的查询。
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| |
如有任何帮助,我们将不胜感激。 谢谢!
我将忽略您主题行中的问题,因为您的示例数据和所需的输出根本不需要 PIVOT。
您可以通过使每一列成为 CASE 表达式来获得所需的输出。在每个 wk**
列中,如果值不为空,return 名字、姓氏首字母(如果需要)和 phone 数字连接在一起的值。