1
In this query, can I do a sort of distinct? A Group By is very slow and there are many fields. Pure distinct does not solve, as there are several fields. How would that be?
DECLARE
@CodTerceiro int = 113773,
@DataVencimentoIni datetime = null,
@DataVencimentoFim datetime = null,
@Pago tinyint = 3
SELECT pw.IdPedidoWeb,
pw.IdPedido,
Convert(DateTime,receber.E1_EMISSAO,103) as DataEmissao ,
Convert(DateTime,receber.E1_VENCTO, 103) as DataVencimento,
pedido.C5_XIDNF AS IdNotaFiscal,
pedido.C5_NOTA AS NroNotaFiscal,
receber.E1_VALOR AS VlrTotalNotaFiscal,
CASE WHEN receber.E1_SALDO > 0
THEN 'Em Aberto'
ELSE 'Pago'
END 'Status',
pw.CodProduto,
pw.QtdItem,
pw.QtdItem * pw.VlrVenda 'VlrProduto'
FROM [dbo].[PedidoWeb] pw
WITH (NOLOCK, INDEX (Ind_PedidoWeb_2))
INNER JOIN Totvs12.dbo.SC5010 pedido
--WITH (NOLOCK)
ON pedido.C5_XPEDSND = pw.IdPedido
INNER JOIN Totvs12.dbo.SE1010 receber
--WITH (NOLOCK)
ON receber.E1_FILIAL + receber.E1_NUM + receber.E1_PREFIXO = pedido.C5_FILIAL + pedido.C5_NOTA + pedido.C5_SERIE
WHERE pw.CodTerceiro = @CodTerceiro
AND Convert(DateTime,receber.E1_VENCTO, 103) >= coalesce (@DataVencimentoIni, Convert(DateTime,receber.E1_VENCTO, 103))
AND Convert(DateTime,receber.E1_VENCTO, 103) <= coalesce (@DataVencimentoFim, Convert(DateTime,receber.E1_VENCTO, 103))
AND
( @Pago = 3
OR @Pago = CASE WHEN receber.E1_SALDO > 0 THEN 1 ELSE 2 END)
AND pedido.D_E_L_E_T_ = ''
AND pw.IdPedidoWEb between '9000000' and '20000000'
In the query below I return only 75 records and in the query above 213
select distinct idpedido from PedidoWeb where codterceiro = 113773 AND IdPedidoWEb between '9000000' and '20000000'
and IdPedido in (select distinct c5_xpedsnd from Totvs12.dbo.SC5010 where C5_Cliente = '113773')
The above query should have the same result, except something I don’t know.
About DISTICT x GROUP BY, I suggest reading the article "Which is faster: DISTINCT or GROUP BY?". Visit https://portosql.wordpress.com/2018/09/02/distinct-x-group-by/
– José Diz
I could confirm that the format of the columns E1_EMISSAO and E1_VENCTO is
aaaammdd
and whether both are declared as char(8)?– José Diz