I'm currently struggling with a (at least for me) pretty complex SQL query.
I'm trying to calculate commissions.
To calculate properly I need to subtract credits from invoices. As there is no direct relationship between invoices and corresponding credits, I'm joining over their positions.
Anyways, I'd like to display each Invoice (and its creditMemo) only once.
DISTINCT however doesn't work here due to the join with the positions (I guess).
So how could I achieve a clean list of all invoices including their creditmemos (if exists) only once each?
I know of the GROUP BY clause. I can not manage to use it without losing accurate invoice values due to missing positions...
Any idea how to manage this case?
(removed unnecessary information)
SELECT DISTINCT
R.DocNum as InvoiceNo,
R.DocDate as Date,
R.CardCode as BusinessPartnerID,
R.CardName as BusinessPartnerName,
R.DocTotal as wVat,
(R.DocTotal - R.VatSum) as NoVat,
SUM(R1.LineTotal) OVER () as R_NoVatAll,
SUM(R1.LineTotal) OVER () + SUM(R1.VatSum) OVER () AS wVatAll,
R.GrosProfit as Gross,
SUM(R1.GrssProfit) OVER () AS GrossAll,
R.VatSum as VatSum,
G.DocNum as G_Gutschriftnummer,
G.DocDate as G_Datum,
G.DocTotal as G_wVat,
(G.DocTotal - G.VatSum) as G_NoVat,
SUM(-G1.LineTotal) OVER () AS G_noVatAll,
SUM(-G1.GrssProfit) OVER () AS G_grossAll,
-G.VatSum as G_Ust,
V.slpName as slpName,
V.Commission as Commission,
(ISNULL(V.Commission,8)/100*R1.GrssProfit) as CommissionValue, (ISNULL(V.Commission,8)/100*-(G1.GrssProfit + G1.VatSum) ) as CommissionValueMinus,
(SUM(-(G1.LineTotal )) OVER()) as CreditAll,
(SUM(R1.GrssProfit) OVER () - SUM(G1.GrssProfit) OVER ()) as CommissionBase,
(SUM(R1.GrssProfit) OVER () - SUM(G1.GrssProfit) OVER ()) * 8/100 as CommissionTotal
FROM OINV R -- Invoices
INNER JOIN INV1 R1 ON R.DocEntry = R1.DocEntry -- InvoicePositions
LEFT JOIN RIN1 G1 ON G1.BaseEntry = R1.DocEntry AND G1.BaseLine = R1.LineNum AND G1.BaseType = 13 -- CreditPositions
FULL JOIN ORIN G ON G1.DocEntry = G.DocEntry -- Credits
LEFT JOIN OSLP V ON G.slpCode = V.slpCode -- SLPs
WHERE 1=1
AND (R.DocDate BETWEEN '07.01.2015' AND '07.31.2015' OR G.DocDate BETWEEN '07.01.2015' AND '07.31.2015')
AND R1.AcctCode <> '9085'
AND R.DocTotal <> 0
AND R.CANCELED <> 'Y'
AND G.DocTotal <> 0
ORDER BY R.DocNum
Related
I'm working on a similar problem to check if a column contains ALL the values of another column - Mysql
This CTE is part of a bigger query. CTE_ProjekteRollen contains a subset of ProjektParamRolle and can contain zero or more records. I want a list of ProjektParam where the items in CTE_ProjekteRollen are all present (when joined with ProjektParamRolle). My solution works in all cases where CTE_ProjektRollen is not empty.
CTE_FilteredByRolle as (
select pp.ID_ProjektParam
from Basis.ProjektParam pp
join Basis.ProjektParamRolle ppr
on pp.ID_ProjektParam = ppr.ID_ProjektParam
join CTE_ProjektRollen pr
on ppr.Rolle = pr.Rolle
group by pp.ID_ProjektParam
having Count(pp.ID_ProjektParam) = (
select Count(Rolle)
from CTE_ProjektRollen))
What do I have to change to get all ProjektParam (joined with ProjektParamRolle), if CTE_ProjektRollen is empty?
Edit: I think I phrased my question wrong, because I didn't understand it fully. #Kendle's solution works for what I described, but I actually needed all ID_ProjektParam (not joined with ProjektParamRolle).
The actual CTE that worked for me was
CTE_FilteredByRolle as (
select pp.ID_ProjektParam
from Basis.ProjektParam pp
where (
select Count(ppr.Rolle)
from Basis.ProjektParamRolle ppr
join CTE_ProjektRollen pr
on ppr.Rolle = pr.Rolle
where ppr.ID_ProjektParam = pp.ID_ProjektParam) = (
select Count(Rolle)
from CTE_ProjektRollen))
We can use a CASE to check whether the table is empty. If it is empty we return the number to which we are comparing, so it will always be true.
CTE_FilteredByRolle as (
select pp.ID_ProjektParam
from Basis.ProjektParam pp
join Basis.ProjektParamRolle ppr
on pp.ID_ProjektParam = ppr.ID_ProjektParam
join CTE_ProjektRollen pr
on ppr.Rolle = pr.Rolle
group by pp.ID_ProjektParam
having Count(distinct pp.ID_ProjektParam)
= case when(select Count(distinct Rolle) from CTE_ProjektRollen)) = 0
then Count(distinct pp.ID_ProjektParam)
else (select Count(distinct Rolle) from CTE_ProjektRollen))
end;
I would like to know what can you do in the following scenario:
Lets say I am filtering on a date in the where clause (between eomonth(#StartDate) and eomonth(getdate()-1). I have a calculated column that is correct when I run the query without any filter, but the problem is that when I filter lets say #StartDate = 06/30/2017 then the calculations will obviously change. Is there any way of doing this?
The calculated column is a windowing function.
Edited:
I have added a picture of the data. So I am using a windowing function to calculate the agentfourmonthperiod. You will see that it sums the units for that month and the 3 previous months. This I dont want to change when filtering. So the units and agentfourmonthperiod columns should stay exactly the same after filtering on the #StartDate. Please see data below:
I want to design an SSRS report that the user will be filtering on the #StartDate, but then it should show the calculation as it does when no filter in used.
Hope this makes sense. Otherwise I can add the code. Its just quite long though.
Code:
WITH DATA
AS
(
SELECT
EOMONTH(SubmissionDates.original_date_c) AS IntakeMonth,
ProvincialArea.SAD_ProvMananger AS ProvManager,
RegionalArea.SAD_RegMananger AS RegManager,
SalesArea.SAD_SalesManager AS AreaSalesManager,
ConsultantUserExt.name AS Consultant,
COUNT(LeadsLink.LeadsID) OVER(PARTITION BY ConsultantUserExt.name, EOMONTH(SubmissionDates.original_date_c,0) ORDER BY EOMONTH(SubmissionDates.original_date_c,0)) AS Unit,
ROW_NUMBER() OVER(PARTITION BY ConsultantUserExt.name, EOMONTH(SubmissionDates.original_date_c,0) ORDER BY EOMONTH(SubmissionDates.original_date_c,0)) AS rn
FROM Import.OobaApplication as Application
LEFT OUTER JOIN Import.OobaApplicant applicant ON application.ApplicationID = applicant.ApplicationID
AND applicant.PrincipleApplication = 'Y'
LEFT OUTER JOIN usr_userext_cstm ON Application.Consultant = usr_userext_cstm.comcorp_key_c
or Application.Consultant = usr_userext_cstm.deal_maker_key_c
or Application.Consultant = usr_userext_cstm.ops_key_c
LEFT OUTER JOIN usr_userext AS ConsultantUserExt ON usr_userext_cstm.id_c = ConsultantUserExt.id AND ConsultantUserExt.deleted = 0
LEFT OUTER JOIN usr_userext_cstm AS ConsultantUserExtCstm on ConsultantUserExt.id = ConsultantUserExtCstm.id_c
LEFT OUTER JOIN CapcubedInternalDB.dbo.ProvincialArea AS ProvincialArea ON ConsultantUserExtCstm.sad_provincialmanager_c = ProvincialArea.ID
LEFT OUTER JOIN CapcubedInternalDB.dbo.RegionalArea AS RegionalArea ON ConsultantUserExtCstm.sad_regionalmanager_c = RegionalArea.ID
LEFT OUTER JOIN CapcubedInternalDB.dbo.SalesArea AS SalesArea ON ConsultantUserExtCstm.sad_salesmanager_c = SalesArea.ID
LEFT OUTER JOIN CapcubedInternalDB.dbo.LeadsLink AS LeadsLink ON Application.ApplicationID = LeadsLink.GroupCode
LEFT OUTER JOIN suitecrmprod.dbo.leads AS SuiteLeads ON LeadsLink.LeadsID = SuiteLeads.ID
--Latest Bank Submission
LEFT OUTER JOIN (SELECT
bankSub.ApplicationID As BankSubAppID, bankSub.SubmissionDate,
bankSub.Bank, bankSub.RequiredLoanAmount,
bankSub.BankCode AS BankSubBankCode
FROM Import.OobaBankSubmission bankSub
LEFT OUTER JOIN Import.OobaBankSubmission later ON bankSub.ApplicationID = later.ApplicationID
AND bankSub.SubmissionDate > later.SubmissionDate
WHERE later.applicationID IS NULL) AS BankSub ON Application.ApplicationID = BankSub.BankSubAppID
LEFT OUTER JOIN ccrep_calendar_cstm AS SubmissionDates ON CONVERT(VARCHAR(10),BankSub.SubmissionDate,101) = SubmissionDates.original_date_c
WHERE SubmissionDates.cc_date_c BETWEEN COALESCE(EOMONTH(#StartDate), '01/31/2016') AND COALESCE(#EndDate, GETDATE(), -1)
AND ConsultantUserExtCstm.consultantstatus_c NOT LIKE 2
)
SELECT *
INTO #Rn
FROM DATA
WHERE rn = 1
SELECT i.IntakeMonth, c.ProvManager, c.RegManager, c.AreaSalesManager, c.Consultant, COALESCE(#Rn.Unit, 0) AS Unit
INTO #FillData
FROM (SELECT DISTINCT IntakeMonth FROM #Rn) AS i
CROSS JOIN
(SELECT DISTINCT Consultant, ProvManager, RegManager, AreaSalesManager FROM #Rn) AS c
LEFT OUTER JOIN #Rn ON #Rn.IntakeMonth = i.IntakeMonth AND #Rn.Consultant = c.Consultant
ORDER BY Consultant, IntakeMonth
SELECT
IntakeMonth,
Consultant,
Unit,
SUM(Unit) OVER(PARTITION BY Consultant ORDER BY Consultant ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS agentfourmonthperiod
FROM #FillData
WHERE ('(All)' IN (#ProvincialManager) OR (ProvManager IN (#ProvincialManager)))
AND ('(All)' IN (#RegionalManager) OR (RegManager IN (#RegionalManager)))
AND ('(All)' IN (#AreaSalesManager) OR (AreaSalesManager IN (#AreaSalesManager)))
AND ('(All)' IN (#Consultant) OR (Consultant IN (#Consultant)))
DROP TABLE #Rn
DROP TABLE #FillData
You could of course remove any filter on dates from the query and apply them directly in the tablix of your report. Obvously, this means that SQL Server has to return all the data each time the report is run, so I guess that this isn't what you want.
For the window function to have access to the previous 3 rows, you will have to include the previous 3 months in your calculation. To achieve this, change the first condition in the WHERE clause in the cte (data) to something like this:
SubmissionDates.cc_date_c
BETWEEN
ISNULL(DATEADD(month, DATEDIFF(month, 0, #StartDate)-3, 0), '01/10/2015')
AND
ISNULL(#EndDate, DATEADD(day, DATEDIFF(day, 0, GETDATE())-1, 0))
As I thought that your date filter logic was wrong, I changed it to include the dates from the beginning of the month rather than from the end.
Now that the previous 3 months are included, we can apply a filter in the end to exclude the previous months from display, but this has to be done after using the window function, for example with another cte:
WITH calc AS (
SELECT
IntakeMonth,
Consultant,
Unit,
SUM(Unit) OVER(PARTITION BY Consultant ORDER BY Consultant ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS agentfourmonthperiod
FROM #FillData
WHERE ('(All)' IN (#ProvincialManager) OR (ProvManager IN (#ProvincialManager)))
AND ('(All)' IN (#RegionalManager) OR (RegManager IN (#RegionalManager)))
AND ('(All)' IN (#AreaSalesManager) OR (AreaSalesManager IN (#AreaSalesManager)))
AND ('(All)' IN (#Consultant) OR (Consultant IN (#Consultant)))
)
SELECT IntakeMonth, Consultant, Unit, agentfourmonthperiod
FROM calc
WHERE IntakeMonth >= ISNULL(EOMONTH(#StartDate), '01/31/2016')
I'm working on a comparison query that will compare what was processed for the different credit card types versus what was actually processed by our POS service. I have ran into an issue where I am not seeing rows for certain card types if they did not process any payments on a given day but may have given a refund. IE: Nothing purchased with VISA but a VISA refund was given, but due to no purchases the row does not show up even though there's a refund for that type.
Here is my query:
WITH tran_total AS (
SELECT CONCAT(c.id_str, ' - ', c.clinic_str) AS Clinics,
t.clinic,
c.xcharge_mid,
p.pay_desc,
CAST(t.time_ran AS date) AS tran_date,
CASE WHEN SUM(t.amount) <> 0 THEN SUM(t.amount) * - 1
ELSE 0.00 END AS collection
FROM dbo.transactions AS t INNER JOIN
dbo.clinic_master AS c ON t.clinic = c.clinic INNER JOIN
dbo.paytype AS p ON t.clinic = p.clinic AND t.paytype_id = p.paytype_id
WHERE (t.time_ran > GETDATE() - 10)
AND (t.paytype_id IS NOT NULL)
AND (p.pay_desc = 'Visa' OR
p.pay_desc = 'MasterCard' OR
p.pay_desc = 'American Express' OR
p.pay_desc = 'Discover')
GROUP BY c.id_str, c.clinic_str, t.clinic, c.xcharge_mid, p.pay_desc, CAST(t.time_ran AS date))
SELECT w.Clinics,
w.pay_desc,
w.tran_date,
w.collection,
CASE WHEN w.pay_desc = 'Visa' THEN (SUM(VI_pur) - SUM(VI_ref))
WHEN w.pay_desc = 'MasterCard' THEN (SUM(MC_pur) - SUM(MC_ref))
WHEN w.pay_desc = 'American Express' THEN (SUM(AX_pur) - SUM(AX_ref))
WHEN w.pay_desc = 'Discover' THEN (SUM(DI_pur) - SUM(DI_ref)) END AS xcharge
FROM tran_total AS w LEFT OUTER JOIN
dbo.xcharge AS x ON w.xcharge_mid = x.xcharge_mid AND w.tran_date = x.settle_date
GROUP BY w.Clinics, w.pay_desc, w.tran_date, w.collection
ORDER BY w.Clinics, w.tran_date
I've thought about switching this around and starting with the comparison from the xcharge table but there is not a pay_desc that links those easily and if something is processed as the wrong card (VISA is chosen but Discover is scanned) then I feel the rows would be missed still.
What I would like, is for all of the pay_desc to show up for each tran_date even if the SUM(t.amount) does not have a value. I've tried a case statement to accomplish this without any luck.
EDIT: I feel the issue is more due to the t.time_ran variable. If there isn't a payment for a given pay_desc then there won't be a t.time_ran either, is there a function I can do to list out dates between GETDATE()-10 AND GETDATE() kind of thing and just have the t.time_ran and x.settle_date match up to that variable instead?
Any thoughts on this? Thanks in advance
UPDATE:
I have created a calendar table with individual dates and have tried the following query:
WITH tran_test AS(
SELECT cal.calendardate AS cd,
p.clinic,
p.pay_desc,
p.paytype_id
FROM calendar cal, paytype p
WHERE cal.calendardate BETWEEN GETDATE()-10 AND GETDATE()+1
AND (p.pay_desc = 'Visa' OR
p.pay_desc = 'MasterCard' OR
p.pay_desc = 'American Express' OR
p.pay_desc = 'Discover'))
SELECT w.cd,
CONCAT(c.id_str, ' - ', c.clinic_str) AS Clinics,
w.pay_desc,
ISNULL(SUM(t.amount)*-1, 0) AS collection,
CASE WHEN w.pay_desc = 'Visa' THEN (SUM(x.VI_pur) - SUM(x.VI_ref))
WHEN w.pay_desc = 'MasterCard' THEN (SUM(x.MC_pur) - SUM(x.MC_ref))
WHEN w.pay_desc = 'American Express' THEN (SUM(x.AX_pur) - SUM(x.AX_ref))
WHEN w.pay_desc = 'Discover' THEN (SUM(x.DI_pur) - SUM(x.DI_ref)) END AS xcharge
FROM tran_test w
INNER JOIN clinic_master c
ON (w.clinic=c.clinic)
LEFT OUTER JOIN transactions t
ON (t.clinic=w.clinic AND t.paytype_id=w.paytype_id AND CAST(t.time_ran AS date) = w.cd)
LEFT OUTER JOIN xcharge x
ON (w.cd=x.settle_date AND c.xcharge_mid=x.xcharge_mid)
GROUP BY w.cd, c.id_str, c.clinic_str, w.pay_desc
ORDER BY w.cd
However, I'm not getting an issue where my xcharge column seems to multiplying itself by random intervals and I'm not sure why.
It sounds like what you need is a Calendar table. You can generate one as part of a CTE (many examples on this site or just search Google), but IMO you should have a persistent table in your database. This way you can mark certain days as bank holidays, what quarter your business considers them to be in, etc.
Once you have that table in place you can SELECT your dates from that table and then LEFT OUTER JOIN to that table from your Transactions table. Any dates without matching rows in Transactions will still show up with a row, but you'll have 0.00 value for your SUM.
I have a small challenge trying to create a "work in progress view"
I'm not convinced my statement is the best or correct and resulted in an error "Subquery returned more than 1 value"
I have three key tables;
Tasks
PurchaseOrderItem
Resource
There is a unique reference field across all the tables e.g. Tasks.TA_SEQ, PurchaseOrderItem.TA_SEQ and Resource.TA_SEQ
I need to sum different totals from all these tables and the relationship are as follows;
1 Task - many PurchaseOrderItem
1 Task - many Resources
I need to sum all the Purchase order cost values (line items can vary) against active purchase orders for the Task and also sum all the resource cost (3 people - quantity can vary) against the task, any help would be much appreciated. if I can make it also any easier any advice would be appreciated.
Part of my Query as it stands;
SELECT
dbo.F_TASKS.TA_SEQ,
(
SELECT
SUM(POI_TOTAL)
From F_PO_ITEM
where POI_FKEY_TA_SEQ = dbo.F_TASKS.TA_SEQ
and POI_FKEY_POH_SEQ in
(
select
POH_SEQ
from F_PO_HEAD
where POH_STATUS in ('DORMANT', 'ACTIVE')
)
) AS [Pending PO Cost],
dbo.F_TASKS.TA_PO_COST AS [PO Cost],
dbo.F_TASKS.TA_LABOUR_COST AS [Labour Cost],
dbo.F_TASKS.TA_LABOUR_COST - SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS) AS [New Labour Cost],
-----------Not Working from
(select
SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS)
from F_TASK_TIME
where TT_FKEY_TA_SEQ = dbo.F_TASKS.TA_SEQ) + dbo.F_TASKS.TA_PO_COST AS [Subcontractor Costs],
(SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS + dbo.F_TASKS.TA_PO_COST)) * 0.12 AS [Subcontractor Uplift],
((SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS + dbo.F_TASKS.TA_PO_COST)) * 0.12) + (SUM(dbo.F_TASK_TIME.TT_OTHER_COSTS + dbo.F_TASKS.TA_PO_COST)) AS [Subcontractor Uplift Total]
-----------Not Working To
FROM dbo.F_TASKS
LEFT OUTER JOIN dbo.F_TASK_TIME
ON dbo.F_TASKS.TA_SEQ = dbo.F_TASK_TIME.TT_FKEY_TA_SEQ
LEFT OUTER JOIN dbo.F_PO_ITEM
ON dbo.F_TASKS.TA_SEQ = dbo.F_PO_ITEM.POI_FKEY_TA_SEQ
WHERE (dbo.F_TASKS.TA_TASK_DESC = 'BREAKDOWN')
AND (dbo.F_TASKS.TA_PO_COST >= 0)
AND (dbo.F_TASKS.TA_STATUS IN ('ACTIVE', 'ASSIGNED', 'COMPLETE'))
GROUP BY dbo.F_TASKS.TA_PO_COST, dbo.F_TASKS.TA_SEQ, dbo.F_TASKS.TA_LABOUR_COST
Rather than trying to fix your SQL, I'm going to propose a different wau of doing it. I couldn';t easily understand all the wheres in your selects in the select clause, so I've just done the first two.
This approach uses LEFT OUTER JOINs to queries which total by ta_seq. These are guaranteed to return only one row/ta_seq as that's how there're grouped:
SELECT
t.TA_SEQ,
isnull(po.poi_total, 0) [Pending PO Cost],
t.TA_PO_COST AS [PO Cost],
t.TA_LABOUR_COST AS [Labour Cost],
t.TA_LABOUR_COST - isnull(tt.other_costs, 0) AS [New Labour Cost],
-- other cols missed
FROM dbo.F_TASKS t
left outer join
(
t.ta_seq, SUM(POI_TOTAL) poi_total
From F_PO_ITEM poi
where POI_FKEY_POH_SEQ in
(
select
POH_SEQ
from F_PO_HEAD
where POH_STATUS in ('DORMANT', 'ACTIVE')
)
group by t.ta_seq
) po on po.ta_seq = t.ta_seq
left outer join
(
select tt.TT_FKEY_TA_SEQ ta_seq, sum(tt.tt_other_costs) other_costs
from F_TASK_TIME tt
group by tt.TT_FKEY_TA_SEQ
) tt on tt.ta_seq = t.ta_seq
WHERE (t.TA_TASK_DESC = 'BREAKDOWN')
AND (t.TA_PO_COST >= 0)
AND (t.TA_STATUS IN ('ACTIVE', 'ASSIGNED', 'COMPLETE'))
GROUP BY t.TA_PO_COST, t.TA_SEQ, t.TA_LABOUR_COST
I've also used table aliases as I find the schema.tablename format is making me blind (and not helping me decode the missed subqueries).
To put in the missing columns, just translate them into additional LEFT OUTER JOINs as above.
Cheers -
When I run a report for a purchase order, the report duplicates records for product codes.
For example the purchase order is: P000976, the report display the product code twice when it should only appear once. 45-5540 appears twice.
P000976 09-17-2012 15,040.00 15,040.00 0.00
45-5540 "Lordotic Cervical Spacer 10mm
Lordotic Cervical Spacer 10mm" 20 20 0
45-5540 "Lordotic Cervical Spacer 10mm
Lordotic Cervical Spacer 10mm" 20 20 0
When I put the report's SQL in SQL server and run the sql by seeing where the code cause the additional product code it is this line within the SQL:
join all_product_codes_VW p on q.distpartno = p.distpartno
select q.specialrequirement
, q.distpartno
, q.toproduce
, q.prodbegindate
, q.distributor
, rc.report_category_name
, s.productperpo
, r.ebi_released
, w.ebi_in_WIP
, p.distproductname
, tp.typeprefixdetail
, tp.cost
, '1' as ReportTotals
from all_required_vw q
left join all_shipped_grafts_new_VW s on (q.distpartno = s.distpartno and q.specialrequirement = s.ponumber)
left join all_released_Grafts_VW r on q.distpartno = r.distpartno
left join all_in_WIP_VW w on q.distpartno = w.distpartno
join all_product_codes_VW p on q.distpartno = p.distpartno
join setup_tissue_prefix tp on q.typenumber = tp.typeprefix
join setup_report_category_1 rc on q.distributor = rc.report_category_id
where q.prodbegindate < #enddate
and q.completed = '0'
and rc.report_category_name like '%' + isnull(#tcustomer, '') + '%'
order by q.prodbegindate, p.distproductname
This is the SQL for the view for which the join creates the duplicate.
SELECT COUNT_BIG(*) AS BIG, DistPartNo, DistProductName, Distributor, UMTBProductCode
FROM dbo.Setup_Distributor_Product_info
WHERE (Distributor <> '7') OR (Distributor IS NULL)
GROUP BY DistPartNo, DistProductName, Distributor, USSAProductCode
If you comment out these lines
--, p.distproductname
--join all_product_codes_VW p on q.distpartno = p.distpartno
Does the query return single rows for each distpartno? If yes then you're right that the all_products_code_VW view is causing the multiple rows.
Run these two queries and look at how many rows are in each and it will give you a clue as to why this is:
Select * from all_required_vw where distpartno = '45-5540'
Select * from all_product_codes_VW where distpartno = '45-5540'
My guess is that joining on only the distpartno is not enough to give you unique results. There might be more than one distributor for the same part, or multiple productnames for the same part number, e.g. different distrubutors using the the same part number with different products.
Possible this GROUP BY clause
GROUP BY DistPartNo, DistProductName, Distributor, USSAProductCode
need replace on this
GROUP BY DistPartNo, DistProductName, Distributor, UMTBProductCode