INSERT INTO [dbo].[TB02031](
				[TB02031_DTCAD], 
				[TB02031_OPCAD], 
				[TB02031_CODIGO], 
				[TB02031_CUSTO], 
				[TB02031_PERDESC], 
				[TB02031_PRODUTO], 
				[TB02031_PRUNIT], 
				[TB02031_QTPROD], 
				[TB02031_QTPRODB], 
				[TB02031_SITUACAO], 
				[TB02031_TOTVALOR], 
				[TB02031_TOTVALORB], 
				[TB02031_PERCIPI],
				[TB02031_VLRIPI], 
				[TB02031_PERCST], 
				[TB02031_VLRST], 
				[TB02031_REGISTRO], 
				[TB02031_VLRDESC], 
				[TB02031_ICMS], 
				[TB02031_VLRICMS], 
				[TB02031_NATUREZA], 
				[TB02031_VLRFRETE], 
				[TB02031_VLROUTDESP],
				[TB02031_VLRFRETEB], 
				[TB02031_VLROUTDESPB], 
				[TB02031_BASERED], 
				[TB02031_ICMSST], 
				[TB02031_SOMAST], 
				[TB02031_DTENT], 
				[TB02031_BASEICMS], 
				[TB02031_BASEST], 
				[TB02031_CST], 
				[TB02031_OPCOM], 
				[TB02031_COFINS], 
				[TB02031_CSTCOFINS], 
				[TB02031_CSTIPI], 
				[TB02031_CSTPIS], 
				[TB02031_PIS], 
				[TB02031_UNPROD], 
				[TB02031_QTPRODUN])
			SELECT
				GETDATE(),	--[TB02031_DTCAD], 
				'$User',	--[TB02031_OPCAD], 
				Pedido.UltCont,	--[TB02031_CODIGO], 
				SUM(a.TB02112_CUSTO),	--[TB02031_CUSTO], 
				0,	--[TB02031_PERDESC], 
				a.TB02112_PRODUTO,	--[TB02031_PRODUTO], 
				SUM(a.TB02112_CUSTO),	--[TB02031_PRUNIT], 
				COUNT(a.TB02112_NUMSERIE),--[TB02031_QTPROD], 
				0,	--[TB02031_QTPRODB], 
				'A',	--[TB02031_SITUACAO], 
				COUNT(a.TB02112_NUMSERIE),	--[TB02031_TOTVALOR], 
				0,	--[TB02031_TOTVALORB], 
				0,	--[TB02031_PERCIPI],
				0,	--[TB02031_VLRIPI], 
				0,	--[TB02031_PERCST], 
				0,	--[TB02031_VLRST], 
				NULL,	--[TB02031_REGISTRO], 
				0,	--[TB02031_VLRDESC], 
				0,	--[TB02031_ICMS], 
				0,	--[TB02031_VLRICMS], 
				0,	--[TB02031_NATUREZA], 
				0,	--[TB02031_VLRFRETE], 
				0,	--[TB02031_VLROUTDESP],
				0,	--[TB02031_VLRFRETEB], 
				0,	--[TB02031_VLROUTDESPB], 
				0,	--[TB02031_BASERED], 
				0,	--[TB02031_ICMSST], 
				0,	--[TB02031_SOMAST], 
				GETDATE(),	--[TB02031_DTENT], 
				0,	--[TB02031_BASEICMS], 
				0,	--[TB02031_BASEST], 
				0,	--[TB02031_CST], 
				NULL,	--[TB02031_OPCOM], 
				0,	--[TB02031_COFINS], 
				0,	--[TB02031_CSTCOFINS], 
				0,	--[TB02031_CSTIPI], 
				0,	--[TB02031_CSTPIS], 
				0,	--[TB02031_PIS], 
				'00',	--[TB02031_UNPROD], 
				1	--[TB02031_QTPRODUN]
				FROM TB02112 a
				OUTER APPLY(
					SELECT TOP 1 
						TB02030_CODIGO UltCont
					FROM TB02030 
					ORDER BY 1 DESC
				) AS Pedido
					

				WHERE a.TB02112_SITUACAO = 'A'
				    AND a.TB02112_PAT IN ('027306', '027742', '028564')

				GROUP BY a.TB02112_PRODUTO, Pedido.UltCont
