试图优化我的代码而不是使用临时的,对SQL Server来说是新的代码,我编写的代码为我提供了我所需的信息
Create table FI (
tipodoc numeric,
nmdoc varchar(20),
fno numeric,
rdata datetime,
fnoft numeric,
design varchar(60);
Insert into Fi (tipodoc ,
nmdoc,
fno,
rdata ,
fnoft ,
design)
values(1,'FT','18',2017-31-12,null,null),
(2,'NC',1,2018-31-12,18,'FT 18 18-12-2017'),
(1,'FT',1,2018-01-01,null,null),
(2,'NC',1,2018-31-12,1,'FT 1 01-01-2018'),
(1,'FT',2,2018-31-12,null,null),
(2,'NC',1,2019-31-12,5,'FT 2 31-12-2018')
select
Cod_final = convert(int,fi.fnoft+fi.tipodoc+fi.rdata),
fi.tipodoc,
fi.nmdoc,
fi.fno,
fi.rdata,
fi.fnoft,
ltrim(rtrim(CONVERT(varchar(30),replace(right(design,10 ),'.','-')))) as Ftdata
into tempFI
from fi
where fi.nmdoc Like '%Credito' and design like '%factura%';
select
tempFI.Cod_final,
fi.nmdoc,
fi.fno,
convert(date,fi.rdata) as DataDoc,
Fi.fnoft,
tempFI.rdata,
tempfi.Ftdata
from fi
inner join tempfi on fi.fnoft=tempFI.fnoft
where convert(int,fi.fnoft+fi.tipodoc+fi.rdata) = tempFI.Cod_final
and fi.tipodoc =3 and tempfi.ftdata like '%-%-%'
order by tempFI.Cod_final
go
DROP TABLE IF EXISTS tempfi
原始数据 https://docs.google.com/spreadsheets/d/1VCd8ZQVt6ztLNNhUb-FRj1WIAGW8zYZP3AZbx3GaGTs/edit?usp=sharing
我假装和做过的简短说明
Tempfi.cod_final-自从出现问题以来,tipodoc多年来一直在重复自己 相同的fnoft和tipodoc(这与nmdoc关联,有一个与文档类型关联的数字)都是int,所以我转换了rdata,这是创建文档时的datatime,这是我的新数字,因此我可以正确识别。
fno和fnoft-cod_final 42726是fno 8,源自fnoft 1268,来自不同文档类型tipodoc的fno中的数字相同
tempfi.rdata-我正在测试以获取创建文档时tempfi.codfinal日期时间的正确值,但我惨败
tempfi.FTdata。是一个包含fnoft数量和创建日期的字符串,因此我的tempfi.rdata应该与tempfi.ftdata
相同感谢您的帮助,对不起,如果这有点混乱
更新 因此,在阅读了有关CTE的内容后,我已经完成了此操作
with cte_fi2 as
(
select
Cod_final = convert(int,fi.fnoft+fi.tipodoc+fi.rdata),
fi.tipodoc,
fi.nmdoc,
fi.fno,
fi.rdata,
fi.eteliquido
from fi
where fi.tipodoc = 1
),
cte_fi as
(
select
Cod_final = convert(int,fi.fnoft+fi.tipodoc+fi.rdata),
fi.tipodoc,
fi.nmdoc,
fi.fno,
fi.rdata,
fi.fnoft,
ltrim(rtrim(CONVERT(varchar(30),replace(right(design,10 ),'.','-')))) as Ftdata
from fi
where fi.tipodoc=3 and design like '%factura%'
)
select
fi.nmdoc,
fi.fno as NºNC,
convert(date,fi.rdata) as DataNC,
Fi.fnoft as NºFT,
cte_fi2.rdata as DataFTcte2,
cte_fi.ftdata,
from fi
inner join cte_fi on fi.fno=cte_fi.fno
inner join cte_fi2 on fi.fno = cte_fi2.fno
where fi.tipodoc =3 and cte_fi.ftdata like '%-%-%'
order by cte_fi.Cod_final
我对ct2_fi2.rdata仍然有问题,它应该返回与cte_fi.tdata相同的值,ct2_fi2.rdata是fi.tipodoc = 1的日期创建 猜我在内部联接中做错了什么。我还不明白
Nmdoc FNo fi.rdata Fnoft cte_fi2.rdata cte_fi.ftdata
NC 3 2013-02-08 0 08-02-2013 2016-01-04
输出