我有一个包含多值字段(存款,Tax1和tax2)的sql表,如下所示:
ID Account_Number Plan Deposits Tax1 Tax2
10 123456 PRINC10 4;4 4256.45;1567.45 4256.45;1567.45
11 123456 KrINC11 4;4 4256.45;1567.45 4256.45;1567.45
我已使用来自SQL Servercentral.com的DelimiterSplit8K表值函数分隔了多值字段。
我用来将多值字段分开以分隔行的代码如下:
Select [ID], [account_number], [Plan], [Deposits], [Tax1], [Tax2]
From MVTable
Cross apply dbo.DelimitedSplit8K(MVTable.Deposits, ';') as Depositlist
Cross apply dbo.DelimitedSplit8K(MVTable.Tax1, ';') as Tax1List
Cross apply dbo.DelimitedSplit8K(MVTable.Tax2, ';') as Tax2List
`enter code here`Where DepositList.Itemnumber = Tax1list.itemnumber
and Depositlist.itemnumber = Tax2list.itemnumber
但是我收到的数据有些重复
ID account_number Plan Deposits Tax1 Tax2
10 123456 PRINC10 4 4256.45 4256.45
10 123456 PRINC10 4 1567.45 1567.45
11 123456 KrINC11 4 4256.45 4256.45
11 123456 KrINC11 4 1567.45 1567.45
期望的结果应如下所示,我们只希望为每个帐号/ id字段和Tax1和Tax2字段分别分配一个计划字段。
ID account_number Plan Deposits Tax1 Tax2
10 123456 PRINC10 4 4256.45 4256.45
11 123456 KrINC11 4 1567.45 1567.45
答案 0 :(得分:2)
我建议使用另一种分割值的方法:
with cte as (
select id, account_number, plan,
convert(varchar(max), left(deposits, charindex(';', deposits + ';') - 1)) as deposit,
convert(varchar(max), left(tax2, charindex(';', tax2 + ';') - 1)) as tax1,
convert(varchar(max), left(tax2, charindex(';', tax2 + ';') - 1)) as tax2,
convert(varchar(max), stuff(deposits, 1, charindex(';', deposits + ';'), '')) as deposit_rest,
convert(varchar(max), stuff(tax1, 1, charindex(';', tax1 + ';'), '')) as tax1_rest,
convert(varchar(max), stuff(tax2, 1, charindex(';', tax2 + ';'), '')) as tax2_rest
from t
union all
select id, account_number, plan,
convert(varchar(max), left(deposit_rest, charindex(';', deposit_rest + ';') - 1)) as deposit,
convert(varchar(max), left(tax2_rest, charindex(';', tax2_rest + ';') - 1)) as tax1,
convert(varchar(max), left(tax2_rest, charindex(';', tax2_rest + ';') - 1)) as tax2,
convert(varchar(max), stuff(deposit_rest, 1, charindex(';', deposit_rest + ';'), '')) as deposit_rest,
convert(varchar(max), stuff(tax1_rest, 1, charindex(';', tax1_rest + ';'), '')) as tax1_rest,
convert(varchar(max), stuff(tax2_rest, 1, charindex(';', tax2_rest + ';'), '')) as tax2_rest
from cte
where deposit_rest <> ''
)
select *
from cte;
Here是db <>小提琴。
答案 1 :(得分:0)
如果您需要每个acc_number / id一个计划,而不关心tax1
和tax2
,那么您可以使用它,
select id, account_number, [plan],
convert(varchar(max), left(deposits, charindex(';', deposits) - 1)) as deposit,
convert(varchar(max), left(tax2, charindex(';', tax2) - 1)) as tax1,
convert(varchar(max), left(tax2, charindex(';', tax2) - 1)) as tax2
from ##t
输出看起来像
id account_number plan deposit tax1 tax2
10 123456 PRINC10 4 4256.45 4256.45
11 123456 KrINC11 4 4256.45 4256.45