将一列拆分成几列

时间:2016-09-12 19:20:14

标签: sql sql-server pivot

这是第一次发布海报,请原谅不幸。

我在sql中有一个查询,为了简单起见,返回持续时间,业务持续时间和受影响的服务。问题在于,如果受影响的服务,有时它在行中有多个值。例如,它可以是'crm,payrol和scheduling'。见下文。

持续时间业务持续时间影响服务 60 40 crm 100 95工资单 70 70调度 50 45 crm,调度,调度

我想要的是该内部每个值的单独行。像这样:

duration    business duration   impacted service
60                 40                  crm
50                 45                  crm
100                95                payroll
50                 45                payroll
70                 70               scheduling
50                 45               scheduling

你会怎么做?

谢谢!

2 个答案:

答案 0 :(得分:1)

一种方法使用拆分功能。 Google" SQL Server拆分功能"在网上。然后你将有一个分割功能。

然后,您可以使用outer apply执行此操作:

select t.duration, t.business_duration, s.impacted_service
from t outer apply
     (dbo.split(t.impacted_service)) s(impacted_service);

答案 1 :(得分:1)

这是另一个选项

Declare @YourTable table (duration int,[business duration] int,[impacted service] varchar(50))
Insert Into @YourTable values
(60 ,40,'crm'),
(100,95,'payroll'),
(70 ,70,'scheduling'),
(50 ,45,'crm,payroll, scheduling')

Select Distinct 
       A.duration
      ,A.[business duration]
     ,[impacted service] = B.Key_Value
 From  @YourTable A
 Cross Apply (Select * from [dbo].[udf-Str-Parse](A.[impacted service],',')) B

返回

duration    business duration   impacted service
50          45                  crm
50          45                  payroll
50          45                  scheduling
60          40                  crm
70          70                  scheduling
100         95                  payroll

如果需要,解析UDF

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--       Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')

    Returns @ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max))
    As
    Begin
       Declare @XML xml;Set @XML = Cast('<x>' + Replace(@String,@Delimeter,'</x><x>')+'</x>' as XML)
       Insert Into @ReturnTable Select ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM @XML.nodes('x') as T(String)
       Return 
    End