在SQL server中,我需要从给定的输入导出日期和速率。日期将在5之后;速率将在3之后;可以在同一输入中提供多个日期记录和速率记录(将结果中带有逗号的记录连在一起)。
它有两排。第一次有单一日期和比率。第二个有多个日期和费率。在输入字符串中可能有n个日期和速率。请建议和一个简单的SQL查询来派生相同的内容。我只使用2012,所以我不能使用最新的函数。
输入(2行):
;2;1;2;5;20270608;3;100.000000;
;2;203;2;5;19680515;3;100.000000;5;19690515;3;100.000000;5;19700515;3;100.000000;5;19710515;3;100.000000;5;19720515;3;100.000000;
输出日期(2行):
20270608
19680515,19690515,19700515,19710515,19720515
产出率(2行):
100.000000
100.000000,100.000000,100.000000,100.000000,100.000000
发布于 2022-02-18 07:46:36
正如@JamesZ在注释中已经说过的,您可以使用铅函数来完成这一任务。
declare @test varchar(1000) = ';2;203;2;5;19680515;3;100.000000;5;19690515;3;100.000000;5;19700515;3;100.000000;5;19710515;3;100.000000;5;19720515;3;100.000000;'
select string_agg(t2.nextvalue, ',')
from ( select t.value,
lead(value, 1) over (order by one) nextvalue
from ( select '1' as one,
value
from STRING_SPLIT(@test ,';')
where value is not null
and value <> ''
) t
) t2
where t2.value = '5'
结果是
19680515,19690515,19700515,19710515,19720515
想要得到这个价格就这么做吧
where t2.value = '3'
你自己试试吧,在这个DBFiddle中
编辑
由于sql server 2012没有split_string
函数,所以可以使用DelimitedSplit8K函数。
由于它也没有string_agg
函数,所以我们必须使用xml
来代替
然后我们使用材料在开始时去掉额外的,
select stuff ( ( select ',' + t2.nextvalue
from ( select t.item,
lead(item, 1) over (order by one) nextvalue
from ( select '1' as one,
item
from DelimitedSplit8K(@test, ';')
where item is not null
and item <> ''
) t
) t2
where t2.item = '5'
for XML PATH('')
),
1, 1, ''
) as dates
发布于 2022-02-21 13:49:33
谢谢你的回复。我稍微更改了@GuidoG中的响应,编写了查询,而没有使用如下函数,
SELECT
string_agg(t2.nextvalue, ',')
FROM
(
SELECT
t.item,
Lead(item, 1) OVER (
ORDER BY
one
) nextvalue
from
(
SELECT
'1' AS one,
item
from
(
SELECT
split.a.value('.', 'VARCHAR(100)') AS item
from
(
SELECT
cast (
'<m>' + replace(@test, ';', '</m><m>') + '</m>' as xml
) as data
) AS x cross apply data.nodes ('/M') AS split(a)
) AS i
where
item IS NOT null
and item <> ''
) t
) t2
where
t2.item = '5'
https://stackoverflow.com/questions/71168963
复制相似问题