SQL Server:将逗号分隔的单列值拆分为多列

时间:2018-06-23 20:49:08

标签: sql sql-server

现在,我是SQL Server的新手,并尝试拆分以逗号分隔的列值,并且我希望每个数据都具有单独的列。

<android.support.v4.widget.DrawerLayout
    ...
    android:fitsSystemWindows="true">

    <!-- content -->
    ...

    <!-- drawer -->
    <android.support.design.widget.NavigationView
        ...
        android:fitsSystemWindows="true" 
        app:headerLayout="@layout/nav_header" />

<android.support.v4.widget.DrawerLayout>

我希望结果是这样的:

<android.support.design.widget.CoordinatorLayout
    ...
    android:fitsSystemWindows="true">

    <!-- content -->
    ...

<android.support.design.widget.CoordinatorLayout>

任何想法都会受到赞赏,因为我在这里不那么深入?我有2270,2290,2234,2245,2256 ,并将兼容性设置为140,因为我正在使用SQL Server2017。但是我得到的只是

| Split column |
     2270
     2290
     2234

这是查询,其中输出将看起来像我在问题中发布的样子,需要拆分:

String_split

1 个答案:

答案 0 :(得分:0)

您遇到了问题,因为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';