How to optimize SQL query with subqueries - sql-server

I have this query that is taking a long time to execute. I would like to know how to optimize it. What slows it down are the addition subqueries.
This is the query:
SELECT DISTINCT
dbo.Ventas.IdVenta, dbo.Ventas.CodigoVenta, dbo.Ventas.Fecha_Alta, dbo.M_Operadores.Nombre + ' ' + dbo.M_Operadores.Apellidos AS Operador, SUBSTRING(dbo.Ventas.Cliente, 0, CHARINDEX(CHAR(13), dbo.Ventas.Cliente))
AS Cliente, dbo.M_Centros.Centro,
(SELECT SUM(LineaImporte) AS Expr1
FROM dbo.Ventas_Detalle
WHERE (IdVenta = dbo.Ventas.IdVenta)) - dbo.Ventas.Redondeo AS Importe,
(SELECT ISNULL(SUM(dbo.Movimientos_Caja_Detalle.Ajuste), 0) AS Ajuste
FROM dbo.Movimientos_Caja_Detalle INNER JOIN
dbo.Movimientos_Caja ON dbo.Movimientos_Caja_Detalle.IdMovimientoCaja = dbo.Movimientos_Caja.IdMovimientoCaja
WHERE (dbo.Movimientos_Caja.IdVenta = dbo.Ventas.IdVenta)) AS Ajuste,
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_2.Importe), 0) AS Cobrado
FROM dbo.Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_2 INNER JOIN
dbo.Movimientos_Caja AS Movimientos_Caja_2 ON Movimientos_Caja_Detalle_2.IdMovimientoCaja = Movimientos_Caja_2.IdMovimientoCaja
WHERE (Movimientos_Caja_2.IdVenta = dbo.Ventas.IdVenta) OR
(Movimientos_Caja_2.CodigoSobre = dbo.Ventas.CodigoSobre) AND (Movimientos_Caja_2.IdTipoMov_Caja = 7)) AS Cobrado,
(SELECT SUM(LineaImporte) AS Expr1
FROM dbo.Ventas_Detalle AS Ventas_Detalle_1
WHERE (IdVenta = dbo.Ventas.IdVenta)) - dbo.Ventas.Redondeo -
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_1.Importe), 0) AS Cobrado
FROM dbo.Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_1 INNER JOIN
dbo.Movimientos_Caja AS Movimientos_Caja_1 ON Movimientos_Caja_Detalle_1.IdMovimientoCaja = Movimientos_Caja_1.IdMovimientoCaja
WHERE (Movimientos_Caja_1.IdVenta = dbo.Ventas.IdVenta) OR
(Movimientos_Caja_1.CodigoSobre = dbo.Ventas.CodigoSobre) AND (Movimientos_Caja_1.IdTipoMov_Caja = 7)) AS Pendiente,
(SELECT Importe AS expr1
FROM dbo.Vales
WHERE (IdVentaEmision = dbo.Ventas.IdVenta)) AS Vale, dbo.Ventas.CodigoSobre, dbo.Ventas.FechaTerminado, dbo.Ventas.IdCentro_Alta AS IdCentro, dbo.Ventas.FechaEntregado, dbo.Ventas.IdOperador,
dbo.Ventas.FacturaVenta, dbo.Ventas.FechaFactura, dbo.Ventas.EstadoFactura, dbo.Ventas.TipoFactura
FROM dbo.Ventas INNER JOIN
dbo.M_Operadores ON dbo.Ventas.IdOperador = dbo.M_Operadores.IdOperador INNER JOIN
dbo.M_Centros ON dbo.Ventas.IdCentro_Alta = dbo.M_Centros.IdCentro
This is the code after changes based on comments:
SELECT
V.IdVenta, V.CodigoVenta, V.Fecha_Alta, MO.Nombre + ' ' + MO.Apellidos AS Operador, SUBSTRING(V.Cliente, 0, CHARINDEX(CHAR(13), V.Cliente))
AS Cliente, MC.Centro,
(SELECT SUM(LineaImporte) AS Expr1
FROM Ventas_Detalle
WHERE (IdVenta = V.IdVenta)) - V.Redondeo AS Importe,
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle.Ajuste), 0) AS Ajuste
FROM Movimientos_Caja_Detalle INNER JOIN
Movimientos_Caja ON Movimientos_Caja_Detalle.IdMovimientoCaja = Movimientos_Caja.IdMovimientoCaja
WHERE (Movimientos_Caja.IdVenta = V.IdVenta)) AS Ajuste,
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_2.Importe), 0) AS Cobrado
FROM Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_2 INNER JOIN
Movimientos_Caja AS Movimientos_Caja_2 ON Movimientos_Caja_Detalle_2.IdMovimientoCaja = Movimientos_Caja_2.IdMovimientoCaja
WHERE (Movimientos_Caja_2.IdVenta = V.IdVenta) OR
(Movimientos_Caja_2.CodigoSobre = V.CodigoSobre) AND (Movimientos_Caja_2.IdTipoMov_Caja = 7)) AS Cobrado,
(SELECT SUM(LineaImporte) AS Expr1
FROM Ventas_Detalle AS Ventas_Detalle_1
WHERE (IdVenta = V.IdVenta)) - V.Redondeo -
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_1.Importe), 0) AS Cobrado
FROM Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_1 INNER JOIN
Movimientos_Caja AS Movimientos_Caja_1 ON Movimientos_Caja_Detalle_1.IdMovimientoCaja = Movimientos_Caja_1.IdMovimientoCaja
WHERE (Movimientos_Caja_1.IdVenta = V.IdVenta) OR
(Movimientos_Caja_1.CodigoSobre = V.CodigoSobre) AND (Movimientos_Caja_1.IdTipoMov_Caja = 7)) AS Pendiente,
(SELECT Importe AS expr1
FROM Vales
WHERE (IdVentaEmision = V.IdVenta)) AS Vale, V.CodigoSobre, V.FechaTerminado, V.IdCentro_Alta AS IdCentro, V.FechaEntregado, V.IdOperador,
V.FacturaVenta, V.FechaFactura, V.EstadoFactura, V.TipoFactura
FROM Ventas V INNER JOIN
M_Operadores MO ON V.IdOperador = MO.IdOperador INNER JOIN
M_Centros MC ON V.IdCentro_Alta = MC.IdCentro

Related

optimize the query, my query taking more than 5 minutes to execute

my query taking more than 5 minutes to execute can anyone tell me what's wrong in this query, below is the query I try to optimize it but no luck
SELECT DISTINCT
'Freight' AS Expr1000,
'Acknowledged Trip Details' AS detailtype,
sCompanyDesc,
VehicleRegistration.sVehicleRegistrationNumber,
Token.iTokenId,
sTokenNumber,
Token.dtTokenGenerating AS TokenDate,
LoadAssign.sCustomerInvoiceNumber,
dtCustomerInvoiceDate,
FillingPoint.sFillingPointName AS [From],
DecantingPoint.sDecantingPointName AS [To],
CloseLoad.fExpectedFreightAmount AS fExpectedFreightAmount,
ISNULL(PayAdvance.fAdvanceAmount, 0) AS fAdvanceAmount,
CloseLoad.fCommissionAmount AS fCommissionAmount,
CloseLoad.fDecantedQuantity,
0 AS [Shortage Quantity],
0 AS [Shortage Rate],
0 AS [Shortage Amount],
sProductName,
ISNULL((SELECT SUM(ISNULL(JVDetails.fCreditAmount, 0))
FROM Transactions
INNER JOIN JV ON JV.sJVCode = Transactions.sTransactionCode
INNER JOIN JVDetails ON JVDetails.iJVId = JV.iJVId
WHERE CloseLoad.iTokenId = Transactions.iTokenId
AND JV.sDescription = 'Munshiana'),
0) AS Munshiana,
ISNULL(JV.sJVCode, '') + ISNULL(PV.sPVCode, '') AS advdocnum
FROM CloseLoad
INNER JOIN Token ON CloseLoad.iTokenId = Token.iTokenId
INNER JOIN LoadAssign ON CloseLoad.iLoadId = LoadAssign.iLoadId
INNER JOIN FillingPoint ON Token.iFillingPointId = FillingPoint.iFillingPointId
INNER JOIN DecantingPoint ON LoadAssign.iDecantingPointId = DecantingPoint.iDecantingPointId
INNER JOIN Product ON LoadAssign.iProductId = Product.iProductId
INNER JOIN VehicleRegistration ON Token.iVehicleRegistrationId = VehicleRegistration.iVehicleRegistrationId
INNER JOIN Company ON Token.iCompanyId = Company.iCompanyId
LEFT JOIN PayAdvance ON PayAdvance.iTokenId = Token.iTokenId
AND PayAdvance.bIsApproved = 1
LEFT JOIN PV ON PV.iPayAdvanceId = PayAdvance.iPayAdvanceId
AND PayAdvance.bIsApproved = 1
AND PV.bIsApproved = 1
LEFT JOIN JV ON JV.iPayAdvanceId = PayAdvance.iPayAdvanceId
AND PayAdvance.bIsApproved = 1
AND JV.bIsApproved = 1
WHERE CloseLoad.iLoadId NOT IN (SELECT tfrli.iLoadId
FROM TempFreightReceiptLoadInfo tfrli
INNER JOIN FreightReceiptChqInfo ci ON ci.iFreightReceiptChqInfoId = tfrli.iFreightReceiptChqInfoId
INNER JOIN LoadAssign l1 ON l1.iLoadId = tfrli.iLoadId
WHERE ci.bIsApproved = 1
AND l1.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
AND tfrli.sAllocationType = 'Freight')
AND LoadAssign.bIsLoadClose = 1
AND Token.iVehicleRegistrationId = 2644
AND LoadAssign.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
AND Token.iCompanyId IN (1, 2, 3)
AND Token.sDecantingPointType IN ('Domestic', 'Export')
AND LoadAssign.bIsActive = 1
AND Token.bIsLoadVerify = 1;
Execute EXPLAIN to find bottleneck.
EXPLAIN SELECT DISTINCT ...

T-SQL to MS Access SQL

I have a working query in SQL Server, but I fail to convert it to MS Access SQL.
This is the bare working query in SQL Server:
select tblKPIData.id
,tblKPIData.KPI_id
,tblKPI.KPI_Name
,tblKPIData.ImportTimestamp
,tblKPIData.Quantity
,tblKPIData.FinancialMonth
,tblKPIData.FinancialYear
,tblKPIData.Zone_id
,tblZone.ZoneName
,tblKPIData.DMA_id
,tblDMA.DMA_Name
,tblKPIData.TargetOrResult
from tblKPIData
inner join tblKPI
on tblKPI.Id = KPI_id
left outer join tblDMA
on tblDMA.Id = tblKPIData.DMA_id
left outer join tblZone
on tblZone.ID = tblKPIData.Zone_id
inner join tblDashboardKPI
on tblDashboardKPI.KPI_Id = tblKPIData.KPI_id
inner join
( select a.kpi_id
,a.financialMonth
,a.financialYear
,isnull(a.zone_id,0) as zone_id
,isnull(a.dma_id,0) as dma_id
,a.targetorresult
,max(a.importtimestamp) as importtimestamp
from tblKPIData a
group by kpi_id
,financialMonth
,financialYear
,zone_id
,dma_id
,targetorresult) as max_kpi
on (tblKPIData.KPI_id = max_kpi.KPI_id
and tblKPIData.ImportTimestamp = max_kpi.importtimestamp
and tblKPIData.FinancialMonth = max_kpi.FinancialMonth
and tblKPIData.FinancialYear = max_kpi.FinancialYear
and isnull(tblKPIData.Zone_id,0) = isnull(max_kpi.zone_id,0)
and isnull(tblKPIData.DMA_id,0) = isnull(max_kpi.dma_id,0)
and tblKPIData.TargetOrResult = max_kpi.TargetOrResult)
where tblKPIData.FinancialMonth = 'Oct'
and tblKPIData.FinancialYear = 2017
and tblKPIData.KPI_id in (select kpi_id from tblDashboardKPI where tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
and (tblKPIData.Zone_id = 5 or tblKPIData.DMA_id in (select id from tblDMA where Zoneid = 5))
AND ((tblDashboardKPI.Status) = 1)
and ((tblDashboardKPI.Dashboard_Id) = 6)
I know I have to add brackets, but not exactly sure where. This is what I came up with, but I get an error (Join Expression not supported) and it highlites a piece of code on the first join (tblKPI.Id = KPI_id):
select tblKPIData.id
,tblKPIData.KPI_id
,tblKPI.KPI_Name
,tblKPIData.ImportTimestamp
,tblKPIData.Quantity
,tblKPIData.FinancialMonth
,tblKPIData.FinancialYear
,tblKPIData.Zone_id
,tblZone.ZoneName
,tblKPIData.DMA_id
,tblDMA.DMA_Name
,tblKPIData.TargetOrResult
from (((((tblKPIData
inner join tblKPI
on tblKPI.Id = KPI_id)
left outer join tblDMA
on tblDMA.Id = tblKPIData.DMA_id)
left outer join tblZone
on tblZone.ID = tblKPIData.Zone_id)
inner join tblDashboardKPI
on tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
inner join
( select a.kpi_id
,a.financialMonth
,a.financialYear
,isnull(a.zone_id,0) as zone_id
,isnull(a.dma_id,0) as dma_id
,a.targetorresult
,max(a.importtimestamp) as importtimestamp
from tblKPIData a
group by kpi_id
,financialMonth
,financialYear
,zone_id
,dma_id
,targetorresult) as max_kpi
on (tblKPIData.KPI_id = max_kpi.KPI_id)
and tblKPIData.ImportTimestamp = max_kpi.importtimestamp
and tblKPIData.FinancialMonth = max_kpi.FinancialMonth
and tblKPIData.FinancialYear = max_kpi.FinancialYear
and isnull(tblKPIData.Zone_id,0) = isnull(max_kpi.zone_id,0)
and isnull(tblKPIData.DMA_id,0) = isnull(max_kpi.dma_id,0)
and tblKPIData.TargetOrResult = max_kpi.TargetOrResult)
where tblKPIData.FinancialMonth = 'Oct'
and tblKPIData.FinancialYear = 2017
and tblKPIData.KPI_id in (select kpi_id from tblDashboardKPI where tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
and (tblKPIData.Zone_id = 5 or tblKPIData.DMA_id in (select id from tblDMA where Zoneid = 5))
AND ((tblDashboardKPI.Status) = 1)
and ((tblDashboardKPI.Dashboard_Id) = 6)
What am I doing wrong?

SQL if function

I have a view in SQL and I need to get an if function in there, below is my statement.
SELECT TOP (100) PERCENT
dbo.SorDetail.MLineShipDate,
dbo.SorMaster.SalesOrder,
dbo.SorDetail.SalesOrderLine,
dbo.SorMaster.CustomerPoNumber,
dbo.SorMaster.Customer,
dbo.ArCustomer.Name AS CustomerName,
dbo.SorMaster.Salesperson,
dbo.InvMaster.StockCode,
dbo.InvMaster.Description,
dbo.InvMaster.ProductClass,
dbo.ShortOrderOrigOrderQty.OrderUom,
dbo.ShortOrderOrigOrderQty.OrderQty AS OrderQtyOrig,
dbo.ShortOrderOrigOrderQty.LineValue AS LineValueOrig,
ISNULL(dbo.ShortOrderTrimQty.TrimQty, 0) AS OrderQtyTrim,
dbo.SorDetail.MPrice * ISNULL(dbo.ShortOrderTrimQty.TrimQty, 0) AS LineValueTrim,
dbo.SorDetail.MOrderQty AS OrderQtyCurrent,
dbo.SorDetail.MPrice * dbo.SorDetail.MOrderQty AS LineValueCurrent,
dbo.ShortInvoiced.QtyInvoiced AS OrderQtyPicked,
ISNULL(dbo.ShortOrderPicked.NetSalesValue, 0) AS LineValuePicked,
ISNULL(dbo.ShortInvoiced.QtyInvoiced, 0) / dbo.ShortOrderOrigOrderQty.OrderQty * 100 AS [InFull%],
ISNULL(dbo.ShortInvoiced.QtyInvoiced, 0) / dbo.SorDetail.MOrderQty * 100 AS [StockAvailability%],
dbo.SorDetail.MWarehouse,
dbo.SorDetail.MStockDes,
dbo.SorMaster.OrderStatus,
dbo.SorMaster.InterWhSale
FROM dbo.ShortOrderTrimQty
RIGHT OUTER JOIN dbo.SorMaster
INNER JOIN dbo.ShortInvoiced ON dbo.SorMaster.SalesOrder = dbo.ShortInvoiced.SalesOrder
RIGHT OUTER JOIN dbo.SorDetail ON dbo.ShortInvoiced.SalesOrderLine = dbo.SorDetail.SalesOrderLine
AND dbo.ShortInvoiced.SalesOrder = dbo.SorDetail.SalesOrder
AND dbo.SorMaster.SalesOrder = dbo.SorDetail.SalesOrder
LEFT OUTER JOIN dbo.ShortOrderPicked ON dbo.SorDetail.SalesOrderLine = dbo.ShortOrderPicked.SalesOrderLine
AND dbo.SorDetail.SalesOrder = dbo.ShortOrderPicked.SalesOrder
ON dbo.ShortOrderTrimQty.SalesOrderLine = dbo.SorDetail.SalesOrderInitLine
AND dbo.ShortOrderTrimQty.SalesOrder = dbo.SorDetail.SalesOrder
LEFT OUTER JOIN dbo.ShortOrderOrigOrderQty ON dbo.SorDetail.SalesOrderInitLine = dbo.ShortOrderOrigOrderQty.SalesOrderLine
AND dbo.SorDetail.SalesOrder = dbo.ShortOrderOrigOrderQty.SalesOrder
LEFT OUTER JOIN dbo.InvMaster ON dbo.SorDetail.MStockCode = dbo.InvMaster.StockCode
LEFT OUTER JOIN dbo.InvCustProdType ON dbo.SorDetail.MStockCode = dbo.InvCustProdType.KeyField
LEFT OUTER JOIN dbo.ArCustomer ON dbo.SorMaster.Customer = dbo.ArCustomer.Customer
WHERE (dbo.SorDetail.LineType = '1')
AND (dbo.SorMaster.OrderStatus <> '*')
AND (dbo.SorMaster.DocumentType IN ('B', 'O'))
AND (dbo.SorMaster.Customer <> 'FAC002')
AND (dbo.SorMaster.OrderStatus <> '\')
ORDER BY dbo.SorMaster.SalesOrder, dbo.SorDetail.SalesOrderLine
Okay so I need the IF statement to do the following:
IF (IntWhSales = Y, then OrderQtyOrig = OrderQtyCurrent) else OrderQtyOrig
PLEASE help me
The equivalent IF statement in SQL for your request is:
CASE
WHEN IntWhSales = 'Y'
THEN OrderQtyCurrent
ELSE OrderQtyOrig
END
You just plug this code into the SELECT part of your query.
SELECT TOP (100) PERCENT dbo.SorDetail.MLineShipDate
, dbo.SorMaster.SalesOrder
, dbo.SorDetail.SalesOrderLine
, dbo.SorMaster.CustomerPoNumber
, dbo.SorMaster.Customer
...
, CASE
WHEN IntWhSales = 'Y'
THEN OrderQtyCurrent
ELSE OrderQtyOrig
END AS [OrderQuantity]
FROM dbo.ShortOrderTrimQty
RIGHT OUTER JOIN dbo.SorMaster
...
Add this to your select statement:
Case IntWhSales = 'Y' Then OrderQtyCurrent Else OrderQtyOrig End AS [OrderQuantity]

How to avoid to duplicate a subquery in a query

I'm running a query that contains the same subquery two times, one used in a inner join condition and the another in a outer join. I'm highlighting the repeated subquery with **. How can I optimize this in order to run only once?
SELECT DISTINCT dbo.tb_contato.Nome, dbo.tb_contato.id_contato, dbo.tb_contato.Sexo, dbo.tb_contato.codigo, dbo.tb_email.email
FROM dbo.tb_contato INNER JOIN
dbo.tb_email ON dbo.tb_contato.id_contato = dbo.tb_email.id_contato INNER JOIN
dbo.tb_empresa ON dbo.tb_empresa.id_empresa = dbo.tb_contato.id_empresa LEFT OUTER JOIN
(SELECT dbo.tb_interacao.IDContato AS id_contato
FROM dbo.tb_interacao INNER JOIN
**(SELECT MAX(IDInteracao) AS IDIntMax, IDPerfilParticipante AS id_perfil_participante, IDProjeto, IDContato
FROM dbo.tb_interacao AS tb_interacao_2
GROUP BY IDPerfilParticipante, IDProjeto, IDContato)** AS IntMax1 ON dbo.tb_interacao.IDInteracao = IntMax1.IDIntMax INNER JOIN
dbo.tb_projeto ON dbo.tb_interacao.IDProjeto = dbo.tb_projeto.id_projeto INNER JOIN
dbo.tb_status_processo ON dbo.tb_interacao.IDStatusProcesso = dbo.tb_status_processo.id_status_processo
WHERE (dbo.tb_projeto.id_projeto = 2057) AND (dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 7) OR
(dbo.tb_projeto.id_projeto = 2057) AND (dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 6) OR
(dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 6) AND (dbo.tb_projeto.id_grupo = 55) OR
(dbo.tb_interacao.IDPerfilParticipante = 1) AND (dbo.tb_status_processo.id_status_processo = 7) AND (dbo.tb_projeto.id_grupo = 55))
AS ConvidadosOut ON dbo.tb_contato.id_contato = ConvidadosOut.id_contato INNER JOIN
(SELECT tb_interacao_1.IDContato AS id_contato
FROM dbo.tb_interacao AS tb_interacao_1 INNER JOIN
**(SELECT MAX(IDInteracao) AS IDIntMax, IDPerfilParticipante AS id_perfil_participante, IDProjeto, IDContato
FROM dbo.tb_interacao AS tb_interacao_3
GROUP BY IDPerfilParticipante, IDProjeto, IDContato)** AS IntMax2 ON tb_interacao_1.IDInteracao = IntMax2.IDIntMax INNER JOIN
dbo.tb_projeto AS tb_projeto_1 ON tb_interacao_1.IDProjeto = tb_projeto_1.id_projeto INNER JOIN
dbo.tb_status_processo AS tb_status_processo_1 ON tb_interacao_1.IDStatusProcesso = tb_status_processo_1.id_status_processo
WHERE (tb_projeto_1.id_projeto = 181) AND (IntMax2.id_perfil_participante = 1) AND (tb_status_processo_1.id_status_processo = 4) OR
(tb_projeto_1.id_projeto = 1581) AND (IntMax2.id_perfil_participante = 1) AND (tb_status_processo_1.id_status_processo = 5) OR
(IntMax2.id_perfil_participante = 1) AND (tb_status_processo_1.id_status_processo = 6) AND (tb_projeto_1.id_grupo = 62)) AS ConvidadosIn ON
dbo.tb_contato.id_contato = ConvidadosIn.id_contato
WHERE (dbo.tb_email.email_visibility = 0 OR
dbo.tb_email.email_visibility IS NULL) AND (dbo.tb_empresa.id_pais = 1) AND (dbo.tb_contato.Fonte <> 'salesloft_orange' AND
dbo.tb_contato.Fonte <> 'salesloft_int_orange' OR
dbo.tb_contato.Fonte IS NULL) AND (dbo.tb_contato.id_contato_visibility = 1 OR
dbo.tb_contato.id_contato_visibility IS NULL) AND (ConvidadosOut.id_contato IS NULL)
I hope you are using SQL server 2005 or later. You can safely try using Common table expressions for the purpose as stated in your question.
Below is an example of script from adventureworks database:
USE AdventureWorks2008R2;
GO
-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;
GO

Work Around Divide By Zero Error in SQL SELECT

SELECT
*
FROM
RM_Sales_Union
WHERE
DOCDATE >= 'September 1, 2011'
AND DOCDATE < 'October 1, 2011'
AND CUSTNMBR = '2186020'
That query results in an error:
Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
if run as shown.
Excluding the last line AND CUSTNMBR = '2186020' allows the query to complete.
CUSTNMBR is a char(21) field. Divide by zero has me confused.
What is the "correct" way to work around this?
RM_Sales_Union is a union query view:
SELECT ACTNUMBR_1,
ACTNUMBR_2,
ACTNUMBR_3,
ORSLSAMT,
CUSTCLAS,
CUSTNAME,
CUSTNMBR,
SLPRSNID,
DOCABREV,
CSPORNBR,
CURNCYID,
DOCDATE,
DOCNUMBR,
GLPOSTDT,
SLSAMNT,
VOIDSTTS,
SLPRSNFN,
SPRSNSLN,
DocOrigin,
ORFRTAMT,
FRTAMNT,
COMPRCNT,
TRDISAMT,
ORTDISAM,
ORMISCAMT,
ORTAXAMT,
ORCTRXAM
FROM dbo.RM_Sales_Hist
UNION
SELECT ACTNUMBR_1,
ACTNUMBR_2,
ACTNUMBR_3,
ORSLSAMT,
CUSTCLAS,
CUSTNAME,
CUSTNMBR,
SLPRSNID,
DOCABREV,
CSPORNBR,
CURNCYID,
DOCDATE,
DOCNUMBR,
GLPOSTDT,
SLSAMNT,
VOIDSTTS,
SLPRSNFN,
SPRSNSLN,
DocOrigin,
ORFRTAMT,
FRTAMNT,
COMPRCNT,
TRDISAMT,
ORTDISAM,
ORMISCAMT,
ORTAXAMT,
ORCTRXAM
FROM dbo.RM_Sales_Open
RM_Sales_Hist and RM_Sales_Open are views defined as follows:
--RM_Sales_Hist
SELECT dbo.GL_Sales_Accounts.ACTNUMBR_1,
dbo.GL_Sales_Accounts.ACTNUMBR_2,
dbo.GL_Sales_Accounts.ACTNUMBR_3,
ISNULL(dbo.MC020102.ORSLSAMT, dbo.RM30101.SLSAMNT) AS ORSLSAMT,
dbo.RM00101.CUSTCLAS,
dbo.RM00101.CUSTNAME,
dbo.RM00101.CUSTNMBR,
dbo.RM00101.SLPRSNID,
dbo.RM40401.DOCABREV,
dbo.RM30101.CSPORNBR,
dbo.RM30101.CURNCYID,
dbo.RM30101.DOCDATE,
dbo.RM30101.DOCNUMBR,
dbo.RM30101.GLPOSTDT,
dbo.RM30101.SLSAMNT,
dbo.RM30101.VOIDSTTS,
dbo.RM00301.SLPRSNFN,
dbo.RM00301.SPRSNSLN,
'HIST' AS DocOrigin,
ISNULL(dbo.MC020102.ORFRTAMT, dbo.RM30101.FRTAMNT) AS ORFRTAMT,
dbo.RM30101.FRTAMNT,
dbo.RM00301.COMPRCNT,
dbo.RM30101.TRDISAMT,
ISNULL(dbo.MC020102.ORTDISAM, 0) AS ORTDISAM,
ISNULL(dbo.MC020102.ORMISCAMT, 0) AS ORMISCAMT,
ISNULL(dbo.MC020102.ORTAXAMT, 0) AS ORTAXAMT,
ISNULL(dbo.MC020102.ORCTRXAM, 0) AS ORCTRXAM,
dbo.RM00101.STATE
FROM dbo.GL_Sales_Accounts
INNER JOIN dbo.RM30301
ON dbo.GL_Sales_Accounts.DSTINDX = dbo.RM30301.DSTINDX
INNER JOIN dbo.RM30101
ON dbo.RM30301.CUSTNMBR = dbo.RM30101.CUSTNMBR
AND dbo.RM30301.DOCNUMBR = dbo.RM30101.DOCNUMBR
INNER JOIN dbo.RM00101
ON dbo.RM30101.CUSTNMBR = dbo.RM00101.CUSTNMBR
INNER JOIN dbo.RM40401
ON dbo.RM30101.RMDTYPAL = dbo.RM40401.RMDTYPAL
INNER JOIN dbo.RM00301
ON dbo.RM00101.SLPRSNID = dbo.RM00301.SLPRSNID
LEFT OUTER JOIN dbo.MC020102
ON dbo.RM30301.DOCNUMBR = dbo.MC020102.DOCNUMBR
WHERE ( CAST(dbo.RM30301.DOCNUMBR AS VARCHAR(21)) NOT IN (SELECT
CAST(
DOCNUMBR AS
VARCHAR(21)) AS
Expr1
FROM
dbo.Invoices_With_Display_Discounts) )
--RM_Sales_Open
SELECT dbo.GL_Sales_Accounts.ACTNUMBR_1,
dbo.GL_Sales_Accounts.ACTNUMBR_2,
dbo.GL_Sales_Accounts.ACTNUMBR_3,
ISNULL(dbo.MC020102.ORSLSAMT, 0) AS ORSLSAMT,
dbo.RM00101.CUSTCLAS,
dbo.RM00101.CUSTNAME,
dbo.RM00101.CUSTNMBR,
dbo.RM00101.SLPRSNID,
dbo.RM40401.DOCABREV,
dbo.RM20101.CSPORNBR,
dbo.RM20101.CURNCYID,
dbo.RM20101.DOCDATE,
dbo.RM20101.DOCNUMBR,
dbo.RM20101.GLPOSTDT,
dbo.RM20101.SLSAMNT,
dbo.RM20101.VOIDSTTS,
dbo.RM00301.SLPRSNFN,
dbo.RM00301.SPRSNSLN,
'OPEN' AS DocOrigin,
ISNULL(dbo.MC020102.ORFRTAMT, 0) AS ORFRTAMT,
dbo.RM20101.FRTAMNT,
dbo.RM00301.COMPRCNT,
dbo.RM20101.TRDISAMT,
ISNULL(dbo.MC020102.ORTDISAM, 0) AS ORTDISAM,
ISNULL(dbo.MC020102.ORMISCAMT, 0) AS ORMISCAMT,
ISNULL(dbo.MC020102.ORTAXAMT, 0) AS ORTAXAMT,
ISNULL(dbo.MC020102.ORCTRXAM, 0) AS ORCTRXAM,
dbo.RM00101.STATE
FROM dbo.GL_Sales_Accounts
INNER JOIN dbo.RM10101
ON dbo.GL_Sales_Accounts.DSTINDX = dbo.RM10101.DSTINDX
INNER JOIN dbo.RM20101
ON dbo.RM10101.CUSTNMBR = dbo.RM20101.CUSTNMBR
AND dbo.RM10101.DOCNUMBR = dbo.RM20101.DOCNUMBR
INNER JOIN dbo.RM00101
ON dbo.RM20101.CUSTNMBR = dbo.RM00101.CUSTNMBR
INNER JOIN dbo.RM40401
ON dbo.RM20101.RMDTYPAL = dbo.RM40401.RMDTYPAL
INNER JOIN dbo.RM00301
ON dbo.RM00101.SLPRSNID = dbo.RM00301.SLPRSNID
LEFT OUTER JOIN dbo.MC020102
ON dbo.RM10101.DOCNUMBR = dbo.MC020102.DOCNUMBR
WHERE ( CAST(dbo.RM20101.DOCNUMBR AS VARCHAR(21)) NOT IN (SELECT
CAST(
DOCNUMBR AS
varchar(21)) AS
Expr1
FROM
dbo.Invoices_With_Display_Discounts) )
I guess that RM_Sales_Union is a view that contains a division. The filter simply changes something like a COUNT or SUM to give zero, and it is this that is used as divisor
Change it to use something/NULLIF(..., 0) to make the expressions give NULL. Or ISNULL(something/NULLIF(..., 0), 0) to get NULL instead

Resources