簡體   English   中英

SQL Server:將逗號分隔的單列值拆分為多列

[英]SQL Server : Split a single column value comma seperated to multiple columns

現在,我是SQL Server的新手,並嘗試拆分以逗號分隔的列值,並且我希望每個數據都具有單獨的列。

2270,2290,2234,2245,2256

我希望結果是這樣的:

| Split column |
     2270
     2290
     2234

如果我不在這里,您有什么想法會受到贊賞嗎? 我具有String_split並將兼容性設置為140,因為我正在使用SQL Server 2017.但是我得到的只是

  2270,2290,2234
  2270,2290,2234
  2270,2290,2234

這是查詢,其中輸出將看起來像我在問題中發布的樣子,需要拆分:

SELECT ERSBusinessLogic_InputDataSeries 
FROM [AnimalProductsCoSD].[CoSD].[ERSBusinessLogic]
WHERE
    ERSBusinessLogic_InputGeographyDimensionID = 7493
    AND ERSBusinessLogic_InputTimeDimensionValue = 'all months'
    AND ERSBusinessLogic_Type = 'HS10 aggregation'; 

您遇到了問題,因為split_string()不會保持結果的順序。 啊! 這已經是Microsoft的一項功能請求。

您的字符串的格式看起來很規范。 如果是這樣,您可以只使用substring()

SELECT LEFT(ERSBusinessLogic_InputDataSeries, 4) as str1,
       SUBSTRING(ERSBusinessLogic_InputDataSeries, 5, 4) as str2,
       RIGHT(ERSBusinessLogic_InputDataSeries, 4) as str3
FROM [AnimalProductsCoSD].[CoSD].[ERSBusinessLogic]
WHERE ERSBusinessLogic_InputGeographyDimensionID = 7493 AND
      ERSBusinessLogic_InputTimeDimensionValue = 'all months' AND
      ERSBusinessLogic_Type = 'HS10 aggregation'; 

如果順序無關緊要,則可以使用split_string()

SELECT ss.*
FROM [AnimalProductsCoSD].[CoSD].[ERSBusinessLogic] ebl OUTER APPLY
     (SELECT MAX(CASE WHEN seqnum = 1 THEN val END) as str1,
             MAX(CASE WHEN seqnum = 2 THEN val END) as str2
             MAX(CASE WHEN seqnum = 3 THEN val END) as str3
      FROM (SELECT ss.val, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as seqnum
            FROM split_string(ERSBusinessLogic_InputDataSeries, ',') ss(val)
           ) ss
     ) ss
WHERE ERSBusinessLogic_InputGeographyDimensionID = 7493 AND
      ERSBusinessLogic_InputTimeDimensionValue = 'all months' AND
      ERSBusinessLogic_Type = 'HS10 aggregation'; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM