SQL Server 对逗号分隔值列使用String_split和透视函数

k5ifujac  于 2023-01-04  发布在  其他
关注(0)|答案(1)|浏览(137)

我正在尝试string_splita逗号分隔值列,然后透视结果值到周、日、小时。最后,我需要按sub_issue_keyassignee对数值进行分组。下面是数据示例,表名为dbo. brut_data
| 子任务键(唯一值)|受让人(仅限英文字母)|Σ剩余估计值|
| - ------| - ------| - ------|
| 开发人员-1|西泽股份公司|1周3天7小时|
| 开发人员-2|西泽股份公司|2天6小时|
| 单元测试-1|埃兹阿克|6小时|
下面是我所做的,这段代码拆分[Σ Remaining Estimate]列并将其返回到多行中

SELECT sub_task_key, [Assignee],  value
FROM dbo.brut_data
CROSS APPLY STRING_SPLIT([Σ Remaining Estimate], ',') AS s

但是我不知道如何旋转才能达到这个结果,谁能帮我一把谢谢
想要的结果:
| 子任务键|受让人|周|天|小时|
| - ------| - ------| - ------| - ------| - ------|
| 开发人员-1|西泽股份公司|1个|三个|七|
| 开发人员-2|西泽股份公司||第二章|六个|
| 单元测试-1|埃兹阿克|||六个|

svujldwt

svujldwt1#

尝试使用STRING_SPLIT函数和条件聚合透视数据:

SELECT T.sub_task_key, T.Assignee,
  ISNULL
  (
    MAX(Case When S.value Like '%week%' Then TRIM('weeks ' FROM S.value) End) 
    , 0
  ) AS weeks,
  ISNULL
  (
    MAX(Case When S.value Like '%day%' Then TRIM('days ' FROM S.value) End) 
    , 0
  ) AS days,
  ISNULL
  (
    MAX(Case When S.value Like '%hour%' Then TRIM('hours ' FROM S.value) End) 
    , 0
  ) AS hours
FROM brut_data T CROSS APPLY 
     STRING_SPLIT(T.Remaining_Estimate, ',') S
GROUP BY T.sub_task_key, T.Assignee
ORDER BY T.sub_task_key, T.Assignee

或者,可以按如下方式使用透视运算符:

SELECT sub_task_key, Assignee,
 ISNULL(TRIM('weeks ' FROM w), 0) AS weeks,
 ISNULL(TRIM('days ' FROM d), 0) AS days,
 ISNULL(TRIM('hours ' FROM h), 0) AS hours  
FROM
( 
  SELECT T.sub_task_key, T.Assignee,
         S.value,
         CASE 
          WHEN S.value LIKE '%week%' THEN 'w'
          WHEN S.value LIKE '%day%' THEN 'd'
          WHEN S.value LIKE '%hour%' THEN 'h'
         END AS intervals 
  FROM brut_data T CROSS APPLY 
       STRING_SPLIT(T.Remaining_Estimate, ',') S
) D
PIVOT 
(
  MAX(value) FOR intervals IN ([w], [d], [h])
) P
ORDER BY sub_task_key, Assignee

See demo

相关问题