Boas pessoal
SQL não é meu forte, mas fiz uma query para identificar cadastros que possuem vínculos com outros cadastros e possuem a mesma base.
Está funcionando (aparentemente ^^) porem acredito ter feito de uma forma menos pratica, então como eu poderia melhorar esse script?
select distinct
SUBSTRING(B1.STCD1KNA1,1,8) [Base CNPJ]
,B2.KUNNR [Cliente]
,VKORG [Sales Org]
,KUNN2 [Payer]
from B2
INNER JOIN B1 ON B2.KUNNR = B1.KUNNR
WHERE PARVW = 'RG'
AND B2.KUNNR <> KUNN2
and B1.STCD1KNA1 <> ''
and LAND1KNA1 = 'BR'
and SUBSTRING(B1.STCD1KNA1,1,8) in (
select a.[Base CNPJ] from (
select distinct
SUBSTRING(B1.STCD1KNA1,1,8) [Base CNPJ]
,count(SUBSTRING(B1.STCD1KNA1,1,8)) as [qtde A]
from B2
INNER JOIN B1 ON B2.KUNNR = B1.KUNNR
WHERE PARVW = 'RG'
AND B2.KUNNR <> KUNN2
and B1.STCD1KNA1 <> ''
and LAND1KNA1 = 'BR'
group by SUBSTRING(B1.STCD1KNA1,1,8)
having count(SUBSTRING(B1.STCD1KNA1,1,8)) > 1 ) as a
join (
select distinct
(SUBSTRING(B1.STCD1KNA1,1,8)+kunn2) [Base CNPJ]
,count(SUBSTRING(B1.STCD1KNA1,1,8)+kunn2) [qtde B]
from B2
INNER JOIN B1 ON B2.KUNNR = B1.KUNNR
WHERE PARVW = 'RG'
AND B2.KUNNR <> KUNN2
and B1.STCD1KNA1 <> ''
and LAND1KNA1 = 'BR'
group by (SUBSTRING(B1.STCD1KNA1,1,8)+kunn2)
having count(SUBSTRING(B1.STCD1KNA1,1,8)+kunn2) > 1) B on a.[Base CNPJ] = substring(B.[Base CNPJ],1,8)
where [qtde A] <> [qtde B]
)
group by SUBSTRING(B1.STCD1KNA1,1,8), B2.KUNNR, B2.VKORG, B2.KUNN2
order by [Base CNPJ], Payer
Abrax