2017-09-25 148 views
0

我需要使用分隔符分隔列中的一列值,下面是表結構。使用SQL Server按分隔符分隔字符串

create table #a 
(
    id int, 
    timeline varchar(100) 
) 

insert into #a 
values (1, 'Semi Annual Q2 (May/June/July) & Q4 (Nov/Dec/Jan)'), 
     (2, 'Semi Annual Q1 (Feb/Mar/Apr) & Q3 (Aug/Sep/Oct)'), 
     (3, 'Annual Q3 (Aug/Sep/Oct)'), 
     (4, 'Annual Q2 (May/June/July)'), 
     (5, 'Annual Q4 (Nov/Dec/Jan)'), 
     (6, 'Semi Annual Q1 (Jan/Feb/Mar) & Q3 (July/Aug/Sep)') 

select * from #a 

輸出我想通過「/」分隔符分割時間表值並單獨列單獨的一個月,整整一個月應該在序列,它看起來像下面的示例。

ID M1 M2 M3 M4 M5 M6 
--------------------------------------- 
1 May June July Nov Dec Jan 
2 Feb Mar Apr Aug Sep Oct 
3 Aug Sep Oct NULL NULL NULL 
4 May June July NULL NULL NULL 
5 Nov Dec Jan NULL NULL NULL 
6 Jan Feb Mar July Aug Sep 

到目前爲止,我已經試過這樣:

select 
    timeline, 
    substring((substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline) - 1)), 1, charindex('/', substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline) - 1)) - 1) as M1, 
    replace(replace(right(substring(substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline)), 1, charindex(')', substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline)))), charindex('/', reverse(substring(substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline)), 1, charindex(')', substring(timeline, CHARINDEX('(', timeline) + 1, len(timeline))))), 4)), '/', ''), ')', '') as M3 
from 
    #a; 

這不是一個代碼,同時也過於繁瑣。請幫助,如果你有這種方法有效的方法。

+1

Jeff Moden的DelimitedSplit8K函數應該可以做到這一點...你可以在這裏找到它... http://www.sqlservercentral.com/articles/Tally+Table/72993/ –

+1

I al所以推薦Jeff的分配器。但更重要的是,我建議結束存儲分隔數據的做法。它違反了1NF並導致很多痛苦。 –

+0

[如何將逗號分隔值拆分爲列]可能的重複(https://stackoverflow.com/questions/10581772/how-to-split-a-comma-separated-value-to-columns) –

回答

1

在下述溶液中正在使用的SplitCSVToTable8K功能,就是上面提到的相同DelimitedSplit8K功能...

下面介紹如何在解決方案中使用它:

WITH 
    cte_ParseTimeline AS (
     SELECT 
      a.id, 
      rn = ROW_NUMBER() OVER (PARTITION BY a.id ORDER BY sc.ItemNumber), 
      sc.Item 
     FROM 
      #a a 
      CROSS APPLY dbo.SplitCSVToTable8K(REPLACE(REPLACE(a.timeline, '(', '/'), ')', '/'), '/') sc 
     WHERE 
      sc.Item LIKE ('[A-Z][a-z][a-z]') 
      OR 
      sc.Item LIKE ('[A-Z][a-z][a-z][a-z]') 
     ) 
SELECT 
    pt.id, 
    M1 = MAX(CASE WHEN pt.rn = 1 THEN pt.Item END), 
    M2 = MAX(CASE WHEN pt.rn = 2 THEN pt.Item END), 
    M3 = MAX(CASE WHEN pt.rn = 3 THEN pt.Item END), 
    M4 = MAX(CASE WHEN pt.rn = 4 THEN pt.Item END), 
    M5 = MAX(CASE WHEN pt.rn = 5 THEN pt.Item END), 
    M6 = MAX(CASE WHEN pt.rn = 6 THEN pt.Item END) 
FROM 
    cte_ParseTimeline pt 
GROUP BY 
    pt.id; 

結果...

id   M1 M2 M3 M4 M5 M6 
----------- ----- ----- ----- ----- ----- ----- 
1   May June July Nov Dec Jan 
2   Feb Mar Apr Aug Sep Oct 
3   Aug Sep Oct NULL NULL NULL 
4   May June July NULL NULL NULL 
5   Nov Dec Jan NULL NULL NULL 
6   Jan Feb Mar July Aug Sep 
+0

@Jayank - 感謝您的反饋。我很高興能夠做到。 :) –