我有以下字符串
'06/30/2020;58044.373;.001;12/31/2020;58042.373;.003;06/30/2021;78044.373;.007'
我需要将其转换为:
col 1 col 2 col 3
---- ----- -----
06/30/2020 58044.373 .001
12/31/2020 58042.373 .003
06/30/2021 78044.373 .007
我只能使用选择统计信息,不能使用游标或SP。
请帮忙吗?
答案 0 :(得分:2)
STRING_SPLIT
的解决方法(不安全):
WITH cte AS (
SELECT c, value,
ROW_NUMBER() OVER(ORDER BY (SELECT 1)) % 3 AS rn,
(ROW_NUMBER() OVER(ORDER BY (SELECT 1))-1) / 3 AS grp
FROM t
CROSS APPLY STRING_SPLIT(c, ';')
)
SELECT MAX(CASE WHEN rn = 1 THEN value END) AS col1,
MAX(CASE WHEN rn = 2 THEN value END) AS col2,
MAX(CASE WHEN rn = 0 THEN value END) AS col3
FROM cte
GROUP BY c,grp;
答案 1 :(得分:2)
如果您使用SQL Server 2016+,则可以尝试使用JSON内置支持拆分输入字符串。您需要将输入文本转换为有效的JSON数组,并使用带有默认模式的<hibernate-mapping>
<class name="com.hosting.hostinginterface.spring.user.User" table="user">
<id name="id">
<generator class="identity"/>
</id>
<property name="userName" column="username" type="java.lang.String" not-null="true"/>
<property name="firstName" column="firstname" type="java.lang.String" not-null="true"/>
<property name="lastName" column="lastname" type="java.lang.String" not-null="true"/>
<property name="birthdayText" column="birthday" type="java.lang.String" not-null="true"/>
</class>
</hibernate-mapping>
解析此JSON数组。结果是一个包含列OPENJSON()
,key
和value
的表,对于JSON数组,type
列将保留指定数组中元素的索引。 / p>
声明:
key
结果:
DECLARE @json nvarchar(max) = N'06/30/2020;58044.373;.001;12/31/2020;58042.373;.003;06/30/2021;78044.373;.007'
SELECT
MAX(CASE WHEN CONVERT(int, [key]) % 3 = 0 THEN [value] END) AS Col1,
MAX(CASE WHEN CONVERT(int, [key]) % 3 = 1 THEN [value] END) AS Col2,
MAX(CASE WHEN CONVERT(int, [key]) % 3 = 2 THEN [value] END) AS Col3
FROM OPENJSON(CONCAT(N'["', REPLACE(@json, N';', N'","'), N'"]'))
GROUP BY (CONVERT(int, [key]) / 3)