My problem is that I have a subquery that works perfectly, but for this I have to insert the id I want in the variables.
In the @mediaKM_mes variable I select the tbl table by car id; in the @km variable I select the table tblCar by the car id; and in the @kmFeitos I do again select to the table tblAbstacimento by the id of the car;
In order for my query to fill the table as struct I needed to pass the inserted car_id to a @id_carro variable to get the other variables to fetch the desired information.
What happens to me is that I have to be the one to put the number and only fills either with id 15 or with id 21
FirstIdeclarethevariablesthisway:
@id_carrowhichiswhereyouwantedtostorethevalueofthecaridthatappearsoneachline;
@mediaKM_mesistheaveragekmthatthecarmakespermonthandtosaywhichcarwouldusethevariable@id_carro;
@kmStartistheinitialKmthatthecarhadwhenitwasregistered;
@kmFeitosthatisthesumofkmmadebythissamecartoaddwiththe@kmStartandgetthecurrentkm.
--VARIÁVEISdeclare@id_carroasint;declare@mediaKM_mesasdecimal=(select--nv3round(AVG(cast(kmMesasfloat)),0)asmediaKmMesfrom(select--nv2marca,mes,sum(kmfeitos)askmMes,sum(valorReal)aspagoMes,round(cast(avg(media)asfloat),1)asmediaMesfrom(select--nv1*,casewhenLitros=0orkmfeitos=0thennullelsecast(((Litros/kmfeitos)*100)asdecimal(18,1))endasmediafrom(selectc.marcaasmarca,a.KmFeitosaskmfeitos,MONTH(data)asmes,valorPago-ValorDescontoasvalorReal,cast(valorPago/precoLitroasdecimal(18,2))asLitrosfromtblAbastecimentoajointblCarrocona.id_carro=c.id_carrowherec.id_carro=@id_carro)asnova1)asnova2groupbymes,marca)asnova3groupbymarca);declare@kmInicioasdecimal;set@kmInicio=(selectkm_iniciofromtblCarrowhereid_carro=@id_carro)declare@kmFeitosasdecimal;set@kmFeitos=(selectsum(KmFeitos)fromtblAbastecimentowhereid_carro=@id_carro)--CÓDIGOselect--nv3id_Carro,id_despesa,marca,descricao,v,km,cast(v/y_Mesesasdecimal(18,2))asvalorMensal,casewheny_Meses>12theny_Meses-12endasmesPrevistofrom(select--nv2*,cast(Revisao/@mediaKM_mesasdecimal(18,0))asy_Mesesfrom(select--nv1*,km-(@kmInicio+@kmFeitos)asRevisaofrom(selectc.id_carroasid_Carro,d.id_despesaasid_despesa,c.marcaasmarca,d.descricaoasdescricao,kmaskm,valorasvfromtblPrevistaCarropcjointblCarroconpc.id_carro=c.id_carrojointblDespesadonpc.id_despesa=d.id_despesawherec.id_carro=@id_carro)asnv1)asnv2)asnv3