3
How can I use the LIKE for a comparison of two different table fields? I need to compare the first 5 characters of each field. I tried with SUBSTRING and with LEFT, however, the performance gets very bad.
Here are two ways that I applied, with the commentary signaling: 1)
SELECT(SELECT sum(sd3_sub1.D3_QUANT)
FROM SD3010 AS sd3_sub1
WHERE sd3_sub1.D3_TM = '010'
AND YEAR(D3_EMISSAO) = YEAR(sd3.D3_EMISSAO) AND MONTH(D3_EMISSAO) = MONTH(sd3.D3_EMISSAO)
AND sd3_sub1.D3_LOCAL BETWEEN '01' AND '02'
AND sd3_sub1.D3_FILIAL = sd3.D3_FILIAL
/*AQUI UTILIZEI O LEFT*/
AND LEFT(sd3_sub1.D3_CC, 5) = LEFT(sd3.D3_CC,5)
AND sd3_sub1.D_E_L_E_T_ <> '*') AS producao
FROM SD3010 AS sd3
2)
SELECT(SELECT sum(sd3_sub1.D3_QUANT)
FROM SD3010 AS sd3_sub1
WHERE sd3_sub1.D3_TM = '010'
AND YEAR(D3_EMISSAO) = YEAR(sd3.D3_EMISSAO) AND MONTH(D3_EMISSAO) = MONTH(sd3.D3_EMISSAO)
AND sd3_sub1.D3_LOCAL BETWEEN '01' AND '02'
AND sd3_sub1.D3_FILIAL = sd3.D3_FILIAL
/*AQUI UTILIZEI O SUBSTRING*/
AND SUBSTRING(sd3_sub1.D3_CC,1,5) = SUBSTRING(sd3.D3_CC,1,5)
AND sd3_sub1.D_E_L_E_T_ <> '*) AS producao
FROM SD3010 AS sd3
You can put an example of the field value
sd3.D3_EMISSAO
?– Sorack
@Sorack would be a date, for example "20170222"
– Thiago Alessandro
a string representing a date?
– Sorack
@Sorack Yes... =(
– Thiago Alessandro
@Thiagoalessandro: if you run query 1 without comparing column D3_CC, how much faster is the query? // Note that in the WHERE clause of the subconsulta there are constructions that make it non-sargable, which causes full scanning (index or table scan).
– José Diz