LEFT OUTER JOIN MATCHING - sql-server

I have the following query, I modified it to be able to look in a new table called Futuredial_Validation, I wrote all the conditions and the joins but its still don't looking in the table, just in the one called cellscripter, the rest of the query works, I really appreciate any help, thanks:
SELECT row_number() OVER (ORDER BY wms_us.wms_us.rrno.rrdate, wms_us.wms_us.rrno.pono, wms_us.wms_us.transferboxdet.meidhex, att.Date_cleared) AS ROW_ID,
wms_us.wms_us.rrno.pono AS ATT_PO,
wms_us.wms_us.rrno.rrdate AS Received_Date,
CASE
WHEN (wms_us.wms_us.model.modeldesc = 'MIXED')
THEN wms_us.wms_us.transferboxdet.basemodel
ELSE wms_us.wms_us.model.modelbase
END AS Model,
CASE
WHEN LEN(wms_us.wms_us.transferboxdet.meidhex) >= 15
THEN LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
ELSE wms_us.wms_us.transferboxdet.meidhex
END AS IMEI,
/*Check in Futerdial else obtain the values from cellscripter*/
CASE
WHEN (Future.[Error Code] = '1')
THEN Future.LocalTime
ELSE att.Date_cleared
END AS Date_cleared,
CASE
WHEN (Future.[Error Code] = '1')
THEN 'PASS'
ELSE att.Result
END AS Result
FROM wms_us.wms_us.transferboxdoc
INNER JOIN wms_us.wms_us.transferboxdet
ON wms_us.wms_us.transferboxdoc.transferboxdocid = wms_us.wms_us.transferboxdet.transferboxdocid
INNER JOIN wms_us.wms_us.rrno
ON wms_us.wms_us.transferboxdet.rrnoid = wms_us.wms_us.rrno.rrnoid
INNER JOIN wms_us.wms_us.model
ON wms_us.wms_us.transferboxdoc.modelid = wms_us.wms_us.model.modelid
LEFT OUTER JOIN Futerdial.dbo.Futuredial_Validation AS Future
ON Future.IMEI = LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
LEFT OUTER JOIN DRSCSQLQADB01.att_view2.dbo.attview2 AS att
ON att.IMEI = LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
WHERE (wms_us.wms_us.rrno.rrdate > '2016-12-01')

Most likely: either your join specification is not working or the case expression for the [Error Code] is not correct.
Check if you get any values for [Future_imei] and [Error Code] with this:
select
row_id = row_number() over (
order by rrno.rrdate
, rrno.pono
, tbdet.meidhex
, att.Date_cleared)
, att_po = rrno.pono
, Received_Date = rrno.rrdate
, Model=case
when (m.modeldesc = 'mixed')
then tbdet.basemodel
else m.modelbase
end
, imei=case
when len(tbdet.meidhex) >= 15
then left(tbdet.meidhex, 14)
else tbdet.meidhex
end
, [Future_imei] = Future.imei
, Future.[Error Code]
, Date_cleared=case
when (Future.[Error Code] = '1')
then Future.LocalTime
else att.Date_cleared
end
, [Result]=case
when (Future.[Error Code] = '1')
then 'pass'
else att.Result
end
from wms_us.wms_us.transferboxdoc as tbdoc
inner join wms_us.wms_us.transferboxdet as tbdet
on tbdoc.transferboxdocid = tbdet.transferboxdocid
inner join wms_us.wms_us.rrno as rrno
on tbdet.rrnoid = rrno.rrnoid
inner join wms_us.wms_us.model as m
on tbdoc.modelid = m.modelid
left outer join Futerdial.dbo.Futuredial_Validation as Future
on Future.imei = left(tbdet.meidhex, 14)
left outer join drscsqlqadb01.att_view2.dbo.attview2 as att
on att.imei = left(tbdet.meidhex, 14)
where (rrno.rrdate > '2016-12-01')

Related

How to get a windowed function working in WHERE clause

I know that there are quite many threads on "Windowed functions can only appear in the select or ORDER BY clases" topic, but I have read them through and just don't seem to get any of those trick to work for me. So here I go.
My Query you can see below the line. I have highlighted the part of the Query which is "causing" me issues or problems. The thing is that I would like to get
"LocalCurrentAmount not between -1.000000 and 1.000000"
in somehow. I have tried the CTE versioon, but somehow didn't work and my declare tables and then the details view started causing problems.
Would really appreciate your help!
Jaanis
declare #exceptions1 table (CustomerCode varchar(7), Exception_comment varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(3514437,'Exception'),(3500977,'Exception'),(3295142,'Exception'), ...
declare #exceptions2 table (CustomerCode2 varchar(7), Exception_comment2 varchar(15));
insert into #exceptions2 (CustomerCode2, Exception_comment2)
VALUES
(3390437,'VIP SE') ,(3390438,'VIP SE') ,(3390481,'VIP SE'), ...
declare #exceptions3 table (CustomerCode3 varchar(7), Exception_comment3 varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(1530350, 'DK Exception'), (1533834, 'DK Exception'), (1530002, 'DK Exception'), ...
with Details as
(
select ard.AccountsReceivableHeaderID, sum(ard.TransactionAmountOC) as DetailAmountOC , Max(DetailSequenceCode) as DetailSequenceCode, Max( ard.BatchDate) as BatchDate
from dmbase.fAccountsReceivableDetail ard
join dmbase.fAccountsReceivable arh on ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
where ard.BatchDate <= getdate()
group by AccountsReceivableHeaderID
)
SELECT
comp.CompanyCode
,convert(varchar(10),ar.InvoiceDate, 103) as Invoice_date -- dd/MM/yyyy format
,case
when ar.IsCreditMemo = 'Y' then 'Memo (Credit/Debit)'
when ar.InvoiceCode = '0' then 'Payment'
else 'Invoice'
end as Description
,isnull(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) InvoiceSummaryCode
,case
when len(ar.InvoiceSequenceCode) = '1' then CONCAT(ar.InvoiceCode,'-000',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '2' then CONCAT(ar.InvoiceCode,'-00',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '3' then CONCAT(ar.InvoiceCode,'-0',ar.InvoiceSequenceCode)
else CONCAT(ar.InvoiceCode,'-',ar.InvoiceSequenceCode)
end as Invoice#
,**(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+
coalesce(det.DetailAmountOC, 0)) * coalesce(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount**
,(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+ coalesce(det.DetailAmountOC, 0)) AS CurrentAmount
,ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end as OriginalInvoiceAmountOC
,ar.InvoiceCurrencyCode
,cust.CustomerCode
,upper(cust.CustomerName) as CustomerName
from
dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc
ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust
ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat
on ar.InvoiceCode = vat.contractNumber
and ar.InvoiceSequenceCode = vat.invoiceSequence
and cust.CustomerCode = vat.CustomerNumber
and loc.CompanyCode = vat.companyCode
inner join dmbase.dCompany comp
on (ar.CompanyID = comp.CompanyID)
left join dmbase.dAccountsReceivableInvoiceStatus aris
on (aris.ARInvoiceStatusAMID=ar.ARInvoiceStatusAMID)
left hash join Details det
on (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
left join dmbase.dCurrencyExchangeRate cer
on (comp.CompanyCode = cer.CompanyCode
and ar.InvoiceCurrencyCode = cer.CurrencyCode
and case ar.InvoiceDate when '1900-01-01' then getdate() else ar.InvoiceDate end between cer.ValidFrom and cer.ValidTo)
left join dmbase.fContractClosedHeader ccd
on ccd.ContractNumber = ar.InvoiceCode
and ccd.ContractSeqNumber = ar.InvoiceSequenceCode
and ccd.CompanyID = ar.CompanyID
and ccd.ContractNumber!='0'
and ccd.CreditMemoContractNumber != '0'
left join dmbase.fAccountsReceivableHeader cm
on ccd.CreditMemoContractNumber = cm.ContractNumber
and ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
and cm.CompanyID = ccd.CompanyID
where
(aris.ARInvoiceStatusCode = 'OP' or (ar.LastPaymentDate >= getdate())
or (ar.TotalAdjustmentsAmountOC <> 0 and ar.CurrentAmountLC = 0
and (ar.OriginalInvoiceAmountOC + isnull(vat.vatAdjustment, 0) ) + coalesce(det.DetailAmountOC, 0) <> 0)
)
and ar.OriginalInvoiceAmountOC <= 0
and ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
and cust.InternalCustomerType = 'External'
and cust.CustomerName not in ('RR AJM', 'RAMIRENT', 'Ramirent')
and cust.CustomerName not like '%[7][0-9][0-9][0-9]%'
and ar.InvoiceDate <= EOMONTH(getdate(),-3
and cust.CustomerCode NOT IN
(select CustomerCode from #exceptions1
union
select CustomerCode2 from #exceptions2
union
select CustomerCode3 from #exceptions3)
order by Invoice_date
When using a Window function, like you said in your post, you can't use it in the WHERE clause. The common solution, therefore, is to use a CTE and reference it in the WHERE outside of it. I've used your CTE, however, without any kind of sample data this is a total guess. I've also left a lot of comments for you, and changed some other parts of the SQL, as some of the clauses you have will effect your query's performance.
WITH
Details AS
(SELECT ard.AccountsReceivableHeaderID,
SUM(ard.TransactionAmountOC) AS DetailAmountOC,
MAX(DetailSequenceCode) AS DetailSequenceCode,
MAX(ard.BatchDate) AS BatchDate
FROM dmbase.fAccountsReceivableDetail ard
JOIN dmbase.fAccountsReceivable arh ON ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
WHERE ard.BatchDate <= GETDATE()
GROUP BY AccountsReceivableHeaderID),
Summary AS(
SELECT comp.CompanyCode,
CONVERT(varchar(10), ar.InvoiceDate, 103) AS Invoice_date, -- dd/MM/yyyy format
CASE
WHEN ar.IsCreditMemo = 'Y' THEN 'Memo (Credit/Debit)'
WHEN ar.InvoiceCode = '0' THEN 'Payment'
ELSE 'Invoice'
END AS Description,
ISNULL(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) AS InvoiceSummaryCode,
CASE
WHEN LEN(ar.InvoiceSequenceCode) = '1' THEN CONCAT(ar.InvoiceCode, '-000', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '2' THEN CONCAT(ar.InvoiceCode, '-00', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '3' THEN CONCAT(ar.InvoiceCode, '-0', ar.InvoiceSequenceCode)
ELSE CONCAT(ar.InvoiceCode, '-', ar.InvoiceSequenceCode)
END AS Invoice#,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) * COALESCE(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) AS CurrentAmount,
ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END AS OriginalInvoiceAmountOC,
ar.InvoiceCurrencyCode,
cust.CustomerCode,
UPPER(cust.CustomerName) AS CustomerName
FROM dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat ON ar.InvoiceCode = vat.contractNumber
AND ar.InvoiceSequenceCode = vat.invoiceSequence
AND cust.CustomerCode = vat.CustomerNumber
AND loc.CompanyCode = vat.companyCode
INNER JOIN dmbase.dCompany comp ON (ar.CompanyID = comp.CompanyID)
LEFT JOIN dmbase.dAccountsReceivableInvoiceStatus aris ON (aris.ARInvoiceStatusAMID = ar.ARInvoiceStatusAMID)
LEFT HASH JOIN Details det ON (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
LEFT JOIN dmbase.dCurrencyExchangeRate cer ON (comp.CompanyCode = cer.CompanyCode
AND ar.InvoiceCurrencyCode = cer.CurrencyCode
AND CASE ar.InvoiceDate WHEN '1900-01-01' THEN GETDATE()ELSE ar.InvoiceDate END BETWEEN cer.ValidFrom AND cer.ValidTo)
LEFT JOIN dmbase.fContractClosedHeader ccd ON ccd.ContractNumber = ar.InvoiceCode
AND ccd.ContractSeqNumber = ar.InvoiceSequenceCode
AND ccd.CompanyID = ar.CompanyID
AND ccd.ContractNumber != '0'
AND ccd.CreditMemoContractNumber != '0'
LEFT JOIN dmbase.fAccountsReceivableHeader cm ON ccd.CreditMemoContractNumber = cm.ContractNumber
AND ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
AND cm.CompanyID = ccd.CompanyID
WHERE (aris.ARInvoiceStatusCode = 'OP'
OR (ar.LastPaymentDate >= GETDATE())
OR (ar.TotalAdjustmentsAmountOC <> 0
AND ar.CurrentAmountLC = 0
AND (ar.OriginalInvoiceAmountOC + ISNULL(vat.vatAdjustment, 0)) + COALESCE(det.DetailAmountOC, 0) <> 0)) --Why ISNULL for one, COALESCE for the other? Both will make the query non-SARGable
AND ar.OriginalInvoiceAmountOC <= 0
AND ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
AND cust.InternalCustomerType = 'External'
AND cust.CustomerName NOT IN ('RR AJM', 'RAMIRENT', 'Ramirent')
AND cust.CustomerName NOT LIKE '%[7][0-9][0-9][0-9]%' --A leading wildcard is going to perform slow
AND ar.InvoiceDate <= EOMONTH(DATEADD(DAY, -3, GETDATE())) --I have changed this from EOMONTH(GETDATE(), -3 (which made no sense)
AND NOT EXISTS (SELECT 1
FROM #exceptions1 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions2 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION (you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions3 E
WHERE E.CustomerCode = cust.CustomerCode)) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
SELECT *
FROM Summary
WHERE LocalCurrentAmount NOT BETWEEN -1 AND 1
ORDER BY Invoice_date;
It's worth noting that the above sql is completely untested. I do not have access to your server, or data, so I'm purely relying on "my eye" to note any errors.

Duplicate fields in a table, distinct doesn't work

I have the following query:
select distinct
ROW_ID = row_number() over (
order by wms_us.wms_us.rrno.rrdate
, wms_us.wms_us.rrno.pono
, wms_us.wms_us.transferboxdet.meidhex
, att.Date_cleared
)
, ATT_PO = wms_us.wms_us.rrno.pono
, Received_Date = wms_us.wms_us.rrno.rrdate
, IMEI = case
when len(wms_us.wms_us.transferboxdet.meidhex) >= 15
then left(wms_us.wms_us.transferboxdet.meidhex, 14)
else wms_us.wms_us.transferboxdet.meidhex
end
, Model = case
when (wms_us.wms_us.model.modeldesc = 'MIXED')
then wms_us.wms_us.transferboxdet.basemodel
else wms_us.wms_us.model.modelbase
end
, Date_cleared = case
when (Future.[Error Code] = '1')
then Future.LocalTime
else att.Date_cleared
end
, Result = case
when (Future.[Error Code] = '1')
then 'PASS'
else att.Result
end
from wms_us.wms_us.transferboxdoc
inner join wms_us.wms_us.transferboxdet
on wms_us.wms_us.transferboxdoc.transferboxdocid
= wms_us.wms_us.transferboxdet.transferboxdocid
inner join wms_us.wms_us.rrno
on wms_us.wms_us.transferboxdet.rrnoid = wms_us.wms_us.rrno.rrnoid
inner join wms_us.wms_us.model
on wms_us.wms_us.transferboxdoc.modelid = wms_us.wms_us.model.modelid
left join DRSCSQLQADB01.att_view2.dbo.attview2 as att
on att.IMEI = LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
inner join Futerdial.dbo.Futuredial_Validation as Future
on Future.IMEI = wms_us.wms_us.transferboxdet.meidhex
where (wms_us.wms_us.rrno.rrdate > '2016-12-01')
and Future.IMEI = '352130070643357'
I have the IMEI in the table Futuredial_Validation duplicate, I have been trying to use the Distinct just to show me one IMEI but it's not working, there is any alternative that I can use?? Or I am using it wrong?
Attach a picture of what is showing me, I just one be able to see one the first one.
Screenshot
Thanks
For rows to be filtered out by distinct, all values must be the same. In this query it looks like you can just wrap the query in a CTE and filter on ROW_ID = 1.

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