Related
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.
So I have this query driven ssrs report and I have been asked on part of the report to list the engineers that billed the most hours to the project list them in order from most to least... max to min. This is the huge Query.
declare #startDate date
declare #endDate date
set #startDate = GETDATE() -30
set #endDate = GETDATE()
SELECT
PN_B,
PN_A,
Project_Practice,
Date_Closed_UTC,
Project_ID,
Company_Name,
Invoiced_Service_Amount,
AGR_Amt,
Total_Service_Billing,
Project_TCW,
Hrs_Budgeted,
Est_Hours,
Billing_Method,
Project_Total_Hrs,
Project_Hrs_B,
Project_Hrs_NB,
Project_Hrs_NC,
Project_Hrs_Agr,
Project_Status,
Location,
OPP_RECID,
Opportunity_RecID,
AM,
DA,
PM,
PeopleNRole,
PM_Billing_Method_ID
FROM
(
SELECT
PPRS2.PN_B,
PPRS2.PN_A,
PPRS2.Project_Practice,
PPRS2.Date_Closed_UTC,
PPRS2.Project_ID,
PPRS2.Company_Name,
PPRS2.Invoiced_Service_Amount,
PPRS2.AGR_Amt,
PPRS2.Total_Service_Billing,
PPRS2.Project_TCW,
PPRS2.Hrs_Budgeted,
PPRS2.Est_Hours,
PPRS2.Billing_Method,
PPRS2.Project_Total_Hrs,
PPRS2.Project_Hrs_B,
PPRS2.Project_Hrs_NB,
PPRS2.Project_Hrs_NC,
PPRS2.Project_Hrs_Agr,
PPRS2.Project_Status,
PPRS2.Location,
PPRS2.OPP_RECID,
AMDA2.Opportunity_RecID,
AMDA2.AM,
AMDA2.DA,
AMDA2.PM,
PeopleNRole,
PPRS2.PM_BILLING_METHOD_ID
FROM
(
SELECT
PN_B,
PN_A,
Project_Practice,
Date_Closed_UTC,
Project_ID,
Company_Name,
Invoiced_Service_Amount,
AGR_Amt,
Total_Service_Billing,
Project_TCW,
Hrs_Budgeted,
Est_Hours,
Billing_Method,
Project_Total_Hrs,
Project_Hrs_B,
Project_Hrs_NB,
Project_Hrs_NC,
Project_Hrs_Agr,
Project_Status,
Location,
OPP_RECID,
pl2.PeopleNRole,
PM_Billing_Method_ID
FROM
(
SELECT
Table_B.Project_Number AS PN_B,
Table_A.Project_Number AS PN_A,
Table_A.Project_Practice,
Table_A.Date_Closed_UTC,
Table_A.Project_ID,
Table_A.Company_Name,
Table_A.Invoiced_Service_Amount,
Table_A.AGR_Amt,
Table_A.Total_Service_Billing,
Table_B.Project_TCW,
Table_A.Hrs_Budgeted,
Table_A.Est_Hours,
Table_A.Billing_Method,
Table_B.Project_Total_Hrs,
Table_B.Project_Hrs_B,
Table_B.Project_Hrs_NB,
Table_B.Project_Hrs_NC,
Table_B.Project_Hrs_Agr,
Table_A.Project_Status,
Table_A.Location,
Table_A.OPP_RECID,
Table_A.PM_BILLING_METHOD_ID
FROM
(
SELECT
Total_Service_Billing,
AGR_Amt,
Invoiced_Service_Amount,
Sales_Tax_Amount_Total,
Project_Number,
Project_ID,
Date_Closed_UTC,
Est_Hours,
Billing_Method,
Company_Name,
Project_Status,
Project_Practice,
Hrs_Budgeted,
Location,
OPP_RECID,
PM_Billing_Method_ID
FROM
(
SELECT
Project_Service_Totals.Service_Total AS Total_Service_Billing,
Project_Service_Totals.AGR_Amt,
Project_Service_Totals.Service_Invoice_Amt_Total AS Invoiced_Service_Amount,
Project_Service_Totals.Sales_Tax_Amount_Total,
Project_Service_Totals.Project_RecID AS Project_Number,
PM_Project.Project_ID,
PM_Project.Date_Closed_UTC,
PM_Project.Est_Hours,
PM_Project.PM_Billing_Method_ID AS Billing_Method, /* A = Actual Rates F = Fixed Fee for the Inital Project Type */
Company.Company_Name,
PM_Status.Description AS Project_Status,
PM_Type.Description AS Project_Practice,
SUM(v_rpt_Project.hours_budget) AS Hrs_Budgeted,
Owner_Level.Description AS Location,
PM_Project.Opportunity_RecID AS OPP_RECID,
PM_Project.PM_Billing_Method_ID
FROM
(
SELECT
SUM(Service_Invoice_Amt - Sales_Tax) + SUM(BL_AGR_AMT) AS Service_Total,
SUM(BL_AGR_AMT) AS AGR_Amt,
SUM(Service_Invoice_Amt) AS Service_Invoice_Amt_Total,
SUM(Sales_Tax) AS Sales_Tax_Amount_Total,
Project_RecID
FROM
(
SELECT
Billing_Log_RecID,
Invoice_Number,
Invoice_Amount AS Service_Invoice_Amt,
PM_Project_RecID AS Project_RecID,
Sales_Tax_Amount AS Sales_Tax,
AGR_Amount AS BL_AGR_AMT
FROM
Billing_Log AS Billing_Log_1
)
AS Service_Invoice_Total
GROUP BY Project_RecID
)
AS Project_Service_Totals
INNER JOIN
PM_Project
ON
Project_Service_Totals.Project_RecID = PM_Project.PM_Project_RecID
INNER JOIN
Company
ON
PM_Project.Company_RecID = Company.Company_RecID
INNER JOIN
PM_Status
ON
PM_Project.PM_Status_RecID = PM_Status.PM_Status_RecID
INNER JOIN
PM_Type
ON
PM_Project.PM_Type_RecID = PM_Type.PM_Type_RecID
INNER JOIN
v_rpt_Project
ON
PM_Project.PM_Project_RecID = v_rpt_Project.ProjectNbr
INNER JOIN
Owner_Level
ON
PM_Project.Owner_Level_RecID = Owner_Level.Owner_Level_RecID
GROUP BY
Project_Service_Totals.Service_Total,
Project_Service_Totals.AGR_Amt,
Project_Service_Totals.Service_Invoice_Amt_Total,
Project_Service_Totals.Sales_Tax_Amount_Total,
Project_Service_Totals.Project_RecID,
PM_Project.Project_ID,
PM_Project.Date_Closed_UTC,
PM_Project.Est_Hours,
PM_Project.PM_Billing_Method_ID,
Company.Company_Name,
PM_Status.Description,
PM_Type.Description,
Owner_Level.Description,
PM_Project.Opportunity_RecID
)
AS T
)
AS Table_A
INNER JOIN
(
SELECT
Project_Hrs_B,
Project_Hrs_NB,
Project_Hrs_NC,
Project_Total_Hrs,
Project_Hrs_Agr,
Project_TCW,
Project_Number
FROM
(
SELECT
SUM(Hrs_Billable) AS Project_Hrs_B,
SUM(Hrs_NonBillable) AS Project_Hrs_NB,
SUM(Hrs_NoCharge) AS Project_Hrs_NC,
SUM(Hrs_Billable + Hrs_NonBillable + Hrs_NoCharge) AS Project_Total_Hrs,
SUM(Hrs_Agr) AS Project_Hrs_Agr,
SUM(Project_TC) AS Project_TCW,
Project_Number
FROM
(
SELECT
SUM(Hrs_B) AS Hrs_Billable,
SUM(Hrs_NB) AS Hrs_NonBillable,
SUM(Hrs_NC) AS Hrs_NoCharge,
SUM(Agr_Hrs) AS Hrs_Agr,
SUM(TE_TotalCost) AS Project_TC,
Project_Number,
REC_ID,
Full_Name
FROM
(
SELECT
Rec_ID,
Full_Name,
Project_Number,
SUM(VT_Hrs_Agr) AS Agr_Hrs,
SUM(Line_TC) AS TE_TotalCost,
SUM(CASE WHEN Billing_Type = 'B' THEN (TE_Hrs_Inv) ELSE 0 END) AS Hrs_B,
SUM(CASE WHEN Billing_Type = 'NB' THEN (TE_Hrs_Inv) ELSE 0 END) AS Hrs_NB,
SUM(CASE WHEN Billing_Type = 'NC' THEN (TE_Hrs_Inv) ELSE 0 END) AS Hrs_NC
FROM
(
SELECT
VT_Hrs_Cost,
TE_Hrs_Inv,
Line_TC,
VT_Hrs_B,
VT_Hrs_NB,
VT_Hrs_Agr,
Project_Number,
Rec_ID,
Full_Name,
Billing_Type,
Work_Role
FROM
(
SELECT
v_rpt_Time.Hourly_Cost AS VT_Hrs_Cost,
Time_Entry.Hours_Invoiced AS TE_Hrs_Inv,
v_rpt_Time.Hourly_Cost * Time_Entry.Hours_Invoiced AS Line_TC,
v_rpt_Time.Billable_Hrs AS VT_Hrs_B,
v_rpt_Time.NonBillable_Hrs AS VT_Hrs_NB,
v_rpt_Time.AgrHrsCovered AS VT_Hrs_Agr,
Time_Entry.PM_Project_RecID AS Project_Number,
v_rpt_Time.member_recid AS Rec_ID,
v_rpt_Time.first_name + ' ' + v_rpt_Time.last_name AS Full_Name,
v_rpt_Time.option_id AS Billing_Type,
v_rpt_Time.work_role AS Work_Role
FROM
Time_Entry
INNER JOIN
v_rpt_Time
ON
Time_Entry.Time_RecID = v_rpt_Time.Time_RecID
)
AS Project_Hrs
)
AS Project_Hrs_Sorted
GROUP BY
Project_Number,
Billing_Type,
TE_Hrs_Inv,
VT_Hrs_Agr,
Rec_ID,
Full_Name
)
AS Project_Cost
GROUP BY
Project_Number,
Rec_ID,
Full_Name
)
AS Project_Totals
GROUP BY
Project_Number
)
AS B
)
AS Table_B
ON
Table_A.Project_Number = Table_B.Project_Number
) AS PPRS,
/* Section that creates the Column to Row using a CROSS APPLY and STUFF Command with XML */
(
SELECT
Project_Number,
PeopleNRole
FROM
(
SELECT DISTINCT
Base.PeopleNrole,
p1.Project_Number
FROM
(
SELECT DISTINCT
Time_Entry10.PM_Project_RecID AS Project_Number,
(v_rpt_Time10.first_name + ' ' + v_rpt_Time10.last_name /* + ' ' + member10.Role_id Removes the SE from the Name*/) AS PeopleNrole,
Member10.Role_ID AS RoleID
FROM
Time_Entry AS Time_Entry10
INNER JOIN
v_rpt_Time AS v_rpt_Time10
ON
Time_Entry10.Time_RecID = v_rpt_Time10.Time_RecID
INNER JOIN
Member AS Member10
ON
v_rpt_Time10.member_recid = Member10.Member_RecID AND Member10.Role_ID = 'SE'
--order by Time_Entry10.Hours_Bill desc
)
AS P1
CROSS APPLY
(
SELECT
STUFF
(
(
SELECT ', ' + PeopleNrole
FROM
(
SELECT DISTINCT
Time_Entry11.PM_Project_RecID AS Project_Number,
(v_rpt_Time11.first_name + ' ' + v_rpt_Time11.last_name/* + ' ' + member11.Role_id Removes the SE from the Name*/ ) AS PeopleNrole,
Member11.Role_ID
AS
RoleID
FROM
Time_Entry
AS
Time_Entry11
INNER JOIN
v_rpt_Time AS v_rpt_Time11
ON
Time_Entry11.Time_RecID = v_rpt_Time11.Time_RecID
INNER JOIN
Member AS Member11
ON
v_rpt_Time11.member_recid = Member11.Member_RecID AND Member11.Role_ID = 'SE'
--order by Time_Entry11.Hours_Bill desc
)
AS
P2
WHERE
p2.Project_Number = P1.Project_Number
ORDER BY
Time_Entry.Hours_Bill
FOR
XML
PATH(''), TYPE ).value('.', 'varchar(max)'), 1, 1, '')) Base(PeopleNRole))
AS PeopleLink
)
AS pl2
WHERE
PPRS.PN_A = PL2.Project_Number
)
AS PPRS2
INNER JOIN
(
SELECT
Opportunity_RecID,
AM,
DA,
PM
FROM
(
SELECT
N.Opportunity_RecID,
Member_1.First_Name + ' ' + Member_1.Last_Name AS AM,
Member_2.First_Name + ' ' + Member_2.Last_Name AS DA,
Member_3.First_Name + ' ' + Member_3.Last_Name AS PM
FROM
Member AS Member_1
INNER JOIN
(
SELECT DISTINCT
v_rpt_Opportunity3.Opportunity_RecID,
v_rpt_Opportunity3.Sales_Rep1,
v_rpt_Opportunity3.Sales_Rep2,
PM_Project3.Member_ID
FROM
v_rpt_Opportunity AS v_rpt_Opportunity3
INNER JOIN
PM_Project AS PM_Project3
ON
v_rpt_Opportunity3.Opportunity_RecID = PM_Project3.Opportunity_RecID
) AS N
ON
Member_1.Member_ID = N.Sales_Rep1
INNER JOIN
Member AS Member_2
ON
N.Sales_Rep2 = Member_2.Member_ID
INNER JOIN
Member AS Member_3
ON
N.Member_ID = Member_3.Member_ID
)
AS AMDA
)
AS AMDA2
ON
PPRS2.OPP_RECID = AMDA2.Opportunity_RecID
)
AS PPRS_pt1
WHERE
Date_Closed_UTC BETWEEN #Startdate AND #EndDate
AND
Location <> 'AOSCloud'
/* (Location IN(#Division))
AND Per Leslie 8/14/2013 want all divisions listed
(Project_Practice = IN (#Practice)*/
ORDER BY PN_B
I have committed out kind of where I think I needed to edit the query timeentry10 and timeentry11 but I cant do this because order by clause is invalid in views, inline functions, derived tables, subqueries and common table expressions, unless top, offset,or for xml is also specified... So what I did was try to do time_entry.hours_bill desc but it is telling me that I do not have access to the time_entry at that position. What they had before is order by roleid before the for xml. this really has me thrown off because I feel it is over complicated. Any help with this would be great. I also would not be opposed to take the peoplenrole add another column and just get the person with the most hours and add it to the report saying SE with most hours for the business.
the section that gets the peoplenrole is this
* Section that creates the Column to Row using a CROSS APPLY and STUFF Command with XML */
(
SELECT
Project_Number,
PeopleNRole
FROM
(
SELECT DISTINCT
Base.PeopleNrole,
p1.Project_Number
FROM
(
SELECT DISTINCT
Time_Entry10.PM_Project_RecID AS Project_Number,
(v_rpt_Time10.first_name + ' ' + v_rpt_Time10.last_name /* + ' ' + member10.Role_id Removes the SE from the Name*/) AS PeopleNrole,
Member10.Role_ID AS RoleID
FROM
Time_Entry AS Time_Entry10
INNER JOIN
v_rpt_Time AS v_rpt_Time10
ON
Time_Entry10.Time_RecID = v_rpt_Time10.Time_RecID
INNER JOIN
Member AS Member10
ON
v_rpt_Time10.member_recid = Member10.Member_RecID AND Member10.Role_ID = 'SE'
--order by Time_Entry10.Hours_Bill desc
)
AS P1
CROSS APPLY
(
SELECT
STUFF
(
(
SELECT ', ' + PeopleNrole
FROM
(
SELECT DISTINCT
Time_Entry11.PM_Project_RecID AS Project_Number,
(v_rpt_Time11.first_name + ' ' + v_rpt_Time11.last_name/* + ' ' + member11.Role_id Removes the SE from the Name*/ ) AS PeopleNrole,
Member11.Role_ID
AS
RoleID
FROM
Time_Entry
AS
Time_Entry11
INNER JOIN
v_rpt_Time AS v_rpt_Time11
ON
Time_Entry11.Time_RecID = v_rpt_Time11.Time_RecID
INNER JOIN
Member AS Member11
ON
v_rpt_Time11.member_recid = Member11.Member_RecID AND Member11.Role_ID = 'SE'
--order by Time_Entry11.Hours_Bill desc
)
AS
P2
WHERE
p2.Project_Number = P1.Project_Number
ORDER BY
RoleID
FOR
XML
PATH(''), TYPE ).value('.', 'varchar(max)'), 1, 1, '')) Base(PeopleNRole))
AS PeopleLink
)
AS pl2
WHERE
PPRS.PN_A = PL2.Project_Number
)
here is a pic of the data
So quick and dirty I found an SSRS report obviously this same person did that calculated these hours like this
SELECT F_Name, L_Name, Total_TE_Hours_Actual, project_id
FROM (SELECT SUM(TE_Part2.TE_Hours_Actual) AS Total_TE_Hours_Actual, Member.First_Name AS F_Name, Member.Last_Name AS L_Name, TE_Part2.PM_Project_RecID as project_id
FROM
(SELECT TE_Hours_Actual, PM_Project_RecID, Rec_ID
FROM
(SELECT v_rpt_Time.Hourly_Cost AS TE_Hourly_Cost, v_rpt_Time.hours_actual AS TE_Hours_Actual, Time_Entry.PM_Project_RecID, v_rpt_Time.NonBillable_Hrs AS TE_Hours_Non_Billable, v_rpt_Time.member_recid AS Rec_ID
FROM Time_Entry
INNER JOIN v_rpt_Time ON Time_Entry.Time_RecID = v_rpt_Time.Time_RecID
) AS TE_Part1) AS TE_Part2
INNER JOIN Member ON TE_Part2.Rec_ID = Member.Member_RecID
GROUP BY TE_Part2.Rec_ID, Member.First_Name, Member.Last_Name, TE_Part2.PM_Project_RecID) AS TE_Part3
so I put this to a CTE like this
with time_CTE(F_Name, L_Name, Total_TE_Hours_Actual, project_id) as (
SELECT F_Name, L_Name, Total_TE_Hours_Actual, project_id
FROM (SELECT SUM(TE_Part2.TE_Hours_Actual) AS Total_TE_Hours_Actual, Member.First_Name AS F_Name, Member.Last_Name AS L_Name, TE_Part2.PM_Project_RecID as project_id
FROM
(SELECT TE_Hours_Actual, PM_Project_RecID, Rec_ID
FROM
(SELECT v_rpt_Time.Hourly_Cost AS TE_Hourly_Cost, v_rpt_Time.hours_actual AS TE_Hours_Actual, Time_Entry.PM_Project_RecID, v_rpt_Time.NonBillable_Hrs AS TE_Hours_Non_Billable, v_rpt_Time.member_recid AS Rec_ID
FROM Time_Entry
INNER JOIN v_rpt_Time ON Time_Entry.Time_RecID = v_rpt_Time.Time_RecID
) AS TE_Part1) AS TE_Part2
INNER JOIN Member ON TE_Part2.Rec_ID = Member.Member_RecID
GROUP BY TE_Part2.Rec_ID, Member.First_Name, Member.Last_Name, TE_Part2.PM_Project_RecID) AS TE_Part3)
select top 1 f_name + ' ' + l_name as Name, total_TE_Hours_Actual, project_id from time_CTE
where project_id is not null
order by Total_TE_Hours_Actual desc;
I made a new column in my ssrs that said top SE then I did a lookup like this
=lookup (Fields!PN_A.value, Fields!project_id.value, Fields!Name.value, "SETime")
so this satisfied the business user, but I am taking the advice I got here and breaking that main query up into CTEs that thing is way to ugly
Been stuck on this. I have the query and the result set below:
DECLARE #bookdate date = cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), - 1) AS DATE)
DECLARE #offset int = 1
SELECT distinct #bookdate BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,cast(th.TransactionEffectiveDt AS DATE) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,UPPER(ni.IndexName) InsuredName
,isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,'0'
,'0'
,'0'
,bd.YearBuilt YrConstruction
,ln.PROPDed + '%' [% loss ded EQ]
,CAST(bd.BldgNumber AS VARCHAR(255)) BldgNumber
,CONVERT(INT,REPLACE(bd.BuildingValue,',','')) BuildingValue
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',','')) ContentsBLimit
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',','')) ContentsCLimit
,CONVERT(INT,REPLACE(bd.TIBLimit,',','')) TIBLimit
,CONVERT(INT,REPLACE(bd.BILimit,',','')) BILimit
,CONVERT(INT,REPLACE(bd.EDPLimit,',','')) EDPLimit
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.partyinfo pti on pti.Id=ni.ParentId
AND pti.CMMContainer=bp.CMMContainer
and pti.SystemId=bp.SystemId
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.risk r on r.SystemId=bp.SystemId
AND r.CMMContainer=bp.CMMContainer
AND r.ParentId=ln.Id
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
AND bd.ParentId=r.id
AND bd.[Status] = 'ACTIVE'
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd in ('RiskAddr')
AND ad.ParentId = bd.id
INNER JOIN java.transactioninfo th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'Application'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
AND th.TransactionEffectiveDt not like '2016-12%'
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,cast(th.TransactionEffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), '')
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,bd.YearBuilt
,ln.PROPDed + '%'
,CAST(bd.BldgNumber AS VARCHAR(255))
,CONVERT(INT,REPLACE(bd.BuildingValue,',',''))
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',',''))
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',',''))
,CONVERT(INT,REPLACE(bd.TIBLimit,',',''))
,CONVERT(INT,REPLACE(bd.BILimit,',',''))
,CONVERT(INT,REPLACE(bd.EDPLimit,',',''))
ORDER BY PolicyNumber, transactionnumber, bldgnumber
I get this result set:
What I want is to remove the duplicated transaction number 2 as you can see on the picture. I tried doing the max and group by function using the date and it didn't work. I tried it on transaction number, it works but introduced other problems. Is there anyway that I can get one result set? It is not a real duplicate, it has a different date but I only want to get the latest date that's why I figured the max function might work but I have to group by everything and that didn't help much. I have been looking at outer apply but I have never used that and I don't even know how I would use that on this particular problem.
Have you tried first_value?
FIRST_VALUE ( [scalar_expression ] )
OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )
it works like this: you need to write DISTINCT
select **distinct** id,
first_value(transaction_effective_date) over (partition by number (,sup) order by date DESC (latest, ASC for oldest)) as last_trans_date
from table;
Documentation can be found here: https://msdn.microsoft.com/en-us/library/hh213018.aspx
I have the following query which is part of a bigger XML. The issue is that is not writing the 0 value of the ELSE and writes an empty element <SellingLocation> in the XML. I can't find why. This is the query code.
SELECT (
SELECT TOP 1
CASE WHEN COUNT(ac.SKU) > 0
THEN l.ZoneId + ' ' + SUBSTRING(CONVERT(varchar(10), l.Bays), 0, 4)
ELSE 0
END
FROM #ARTSCreditTrans ac
INNER JOIN LocationSKU l ON ac.SKU = l.SKU
WHERE ac.PickTake = 'P'
GROUP BY ZoneId, Bays
)
FOR XML PATH('SellingLocation'), TYPE
#Devart, how can I make the same modification in the case of a query which has more that one option and the filter with the having doesn't look like the solution? For example:
SELECT [text()] = ISNULL((
SELECT TOP 1
CASE WHEN COUNT(oh.OrderNumber) > 0
THEN oh.Latitude
ELSE CASE WHEN td.RegisterID = 80
THEN SUBSTRING(tt.ShipMidInit, 1, CHARINDEX('|', tt.ShipMidInit) - 1)
END
END
FROM OrderHeader oh INNER JOIN TranDetail td ON oh.OrderNumber = td.DocNumber JOIN TranTotal tt ON td.DocNumber = tt.DocNumber
WHERE td.PickTake = 'P'
GROUP BY oh.Latitude, td.RegisterID, tt.ShipMidInit
), '')
FOR XML PATH('Latitude'), TYPE
Try wrapping the 0 in quotes ('):
SELECT (
SELECT TOP 1
CASE WHEN COUNT(ac.SKU) > 0
THEN l.ZoneId + ' ' + SUBSTRING(CONVERT(varchar(10), l.Bays), 0, 4)
ELSE '0'
END
FROM #ARTSCreditTrans ac INNER JOIN LocationSKU l ON ac.SKU = l.SKU
WHERE ac.PickTake = 'P'
GROUP BY ZoneId, Bays
)
FOR XML PATH('SellingLocation')
, TYPE
SELECT [text()] = ISNULL((
SELECT TOP 1 CAST(l.ZoneId AS VARCHAR(100)) + ' ' + CAST(l.Bays AS VARCHAR(5))
FROM #ARTSCreditTrans ac
JOIN dbo.LocationSKU l ON ac.SKU = l.SKU
WHERE ac.PickTake = 'P'
GROUP BY ZoneId, Bays
HAVING COUNT(ac.SKU) > 0
), '0')
FOR XML PATH('SellingLocation'), TYPE
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