Display Only More Than One Unique Customer/Address Per Truck Number - sql

Been working on a project in which a report will generated from the SQL Query. I wish to display all Shipments (based on unique automatic truck ID) which contain any combination of:
Unique Customers (based on Customer Number, more than one Customer
Number per shipment)
Unique Addresses (based on defined Address Field, more than one unique
Address per shipment)
The output should look like this when the code runs correct:
Truck Customer First Address (other addresses) City State ZIP Country
12345 C12345 567 Hummingbird Lane Detroit MI 48610 US
12345 C12345 908 Elm Street Detroit MI 48611 US
12345 C78901 219 Maple Street Lansing MI 49012 US
Here is a sample of the code I been trying to tease out this information:
WITH cte
AS (SELECT DISTINCT shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.Zip
, ads.Country
FROM
dbo.OrderItems AS ori
JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
JOIN dbo.Address AS ads ON ads.addID = oa.addID
JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
AND adst.atcAddressTypeCode = N'SHIP'
JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
AND ori.itmIDInstance = shpo.itmIDInstance
AND ori.olnID = shpo.olnID
AND ori.olnIDInstance = shpo.olnIDInstance
JOIN dbo.Shipments AS shp ON shp.shipmentID = shpo.shpID
WHERE shpo.shpID = shp.shipmentID
AND ven.venCode IS NOT NULL
)
, maxadd
AS (SELECT
aa.venCode
, MAX(Multadd) AS Multadd
FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY cte.shipmentID, cte.CustomerCode ORDER BY cte.shipmentID) Multadd
, cte.shipmentID
, cte.CustomerCode
, cte.CustomerName
, cte.FirstAddress
, cte.SecondAddress
, cte.ThirdAddress
, cte.City
, cte.State
, cte.Zip
, cte.Country
FROM
cte
) AS aa
GROUP BY
aa.CustomerCode
HAVING COUNT (*)>1
)
, maxshp
AS (SELECT
cc.shipmentID
, MAX(cc.Multadd) AS MultVencode
FROM (
SELECT
bb.shipmentID
, bb.CustomerCode
, ROW_NUMBER() OVER (PARTITION BY shipmentID ORDER BY CustomerCode) Multadd
FROM (SELECT DISTINCT cte.shipmentID, cte.CustomerCode FROM cte) AS bb
) AS cc
GROUP BY
cc.shipmentID
HAVING COUNT(*) > 1
)
SELECT
cte.shipmentID
, cte.CustomerCode
, cte.CustomerName
, cte.FirstAddress
, cte.SecondAddress
, cte.ThirdAddress
, cte.City
, cte.State
, cte.Zip
, cte.Country
, maxadd.Multadd AS AddOnShipID
, maxshp.MultVencode AS VenOnShipID
FROM
cte
JOIN maxadd ON maxadd.CustomerCode = cte.CustomerCode
JOIN maxshp ON maxshp.shipmentID = cte.shipmentID
WHERE
(
maxadd.Multadd <> 2
AND maxshp.MultVencode <> 1
)
ORDER BY
cte.shipmentID
, cte.CustomerCode;
This "quasi" works. I have been racking my brain as to why this still is not working. Wondering if a second set of eyes may find something I am overlooking.

SELECT * FROM (SELECT DISTINCT shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.Zip
, CASE WHEN(ads.Country LIKE 'US') THEN N'USA' ELSE 'CANADA' END AS Country
, COUNT (shp.shipmentID) OVER (PARTITION BY shipmentID ORDER BY shp.shpID) AS cntshpID
FROM dbo.OrderItems AS ori
JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
JOIN dbo.Address AS ads ON ads.addID = oa.addID
JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
AND adst.atcAddressTypeCode = N'SHIP'
JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
AND ori.itmIDInstance = shpo.itmIDInstance
AND ori.olnID = shpo.olnID
AND ori.olnIDInstance = shpo.olnIDInstance
JOIN dbo.Shipments AS shp ON shp.shpID = shpo.shipmentID
WHERE shpo.shpID = shp.shipmentID
GROUP BY shp.shipmentID
, ven.CustomerCode
, ven.CustomerName
, ads.FirstAddress
, ads.SecondAddress
, ads.ThirdAddress
, ads.City
, ads.State
, ads.aZip
, ads.Country) AS bb
WHERE bb.cntshpID > 1
ORDER BY shpID ASC
CTE was not the way to go, it overcomplicated something simple.

Related

Use CTE in SQL to flag DUPLICATES and reference in sub-query

So I have the following CTE:
with dupeinv AS (
select * from (
select
tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (partition by tci.t_idoc ORDER BY tci.t_idoc, tci.t_idat DESC) as rn
from [ln106].[dbo].tcisli305100 tci
) as t
where t.rn = 1
)
There are duplicates in the above table ([ln106].[dbo].tcisli305100) , hence the CTE to get single values. I want to format just these values in the below query (prefixed with ---)
select 'JCI' as BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER
, cl.t_pono AS SALES_ORDER_LINE_NUMBER
, CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID
,CASE WHEN cl.t_dqua = 0 or cl.t_dqua is null THEN cl.t_amti ELSE
cl.t_amti / cl.t_dqua END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL
, cl.t_line AS AR_INVOICE_LINE_NUMBER
, cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY
--- , concat(dupeinv.t_idoc,'|',format(dupeinv.t_idat,'MMddyyyy') ---
,ci.t_ccur AS AR_INVOICE_CURRENCY
, ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di on cl.t_doc = di_t_doc
LEFT JOIN (SELECT t_orno,t_pono FROM [ln106].[dbo].ttdsls401100 WHERE t_oltp <> 1 group by t_orno,t_pono) as l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci on cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'
Query doesn't like me referencing it in the main query. Can anyone help, or suggest a better idea?
Your final query should look something like this:
WITH dupeinv AS
(SELECT *
FROM
(SELECT tci.t_idoc,
tci.t_idat,
ROW_NUMBER() OVER (PARTITION BY tci.t_idoc
ORDER BY tci.t_idoc,
tci.t_idat DESC) AS rn
FROM [ln106].[dbo].tcisli305100 tci) AS t
WHERE t.rn = 1 )
SELECT 'JCI' AS BU,
RTRIM(LTRIM(cl.t_orno)) AS SALES_ORDER_NUMBER ,
cl.t_pono AS SALES_ORDER_LINE_NUMBER ,
CONCAT(cl.t_shpm, cl.t_pono, cl.t_idoc) AS SHIPPING_RECORD_ID ,
CASE
WHEN cl.t_dqua = 0
OR cl.t_dqua IS NULL THEN cl.t_amti
ELSE cl.t_amti / cl.t_dqua
END AS AR_INVOICE_LINE_ITEM_PRICE_LOCAL ,
cl.t_line AS AR_INVOICE_LINE_NUMBER ,
cl.t_dqua AS AR_INVOICE_LINE_ITEM_QUANTITY ,
concat(dupeinv.t_idoc,
'|',
format(dupeinv.t_idat, 'MMddyyyy')) ,
ci.t_ccur AS AR_INVOICE_CURRENCY ,
ci.t_idat AS AR_INVOICE_DATE
FROM [ln106].[dbo].tcisli310100 cl
LEFT JOIN [ln106].[dbo].tcisli305100 ci ON cl.t_idoc = ci.t_idoc
LEFT JOIN t di ON cl.t_doc = di_t_doc
LEFT JOIN
(SELECT t_orno,
t_pono
FROM [ln106].[dbo].ttdsls401100
WHERE t_oltp <> 1
GROUP BY t_orno,
t_pono) AS l --Jed 10162020 Changed the join to prevent duplicate records
ON l.t_orno=cl.t_orno COLLATE SQL_Latin1_General_CP1_CI_AS
AND l.t_pono=cl.t_pono
LEFT JOIN dupeinv tci ON cl.r_idoc = ci.t_doc
WHERE ci.t_idat > '2017'

How to get biggest value from 2 or more fields in a subquery

I have a table with customers that I join with a fact table with sales, based on invoices.
What I need from my report is to get in first part the biggest value of sales based on the incoming order type (1,2,3,C,D) for a customer for last year. And in the second part to get the same but for current year. What I get as result from my current query is all incoming order types with the customer revenue made for each of them. I tried with outer apply as subquery to get only the top 1 value ordered by revenue descending, but in the result I get the same - For all order types the customer revenue. Please help! I hope my explanation isn't understood only by me (happens a lot..)
use dwh01;
WITH OrderTypeUsedLY AS
(
SELECT
c.CustomerKey
,c.BranchId
,c.CustomerId
,c.CustomerName
,ISNULL(SUM(y.[Sale_Revenue]), 0) as [Sale_Revenue_LY]
,ISNULL(SUM(y.[Sale_GrossMarginTotal]), 0) as [Sale_GrossMarginTotal_LY]
,y.IncomingOrderTypeId as IncomingOrderType_LY
FROM live.DimCustomer c
left join (SELECT s.CustomerKey,iot.IncomingOrderTypeid, s.[Sale_Revenue], s.[Sale_GrossMarginTotal] FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d
on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType iot on iot.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where s.ReportCurrencyId = 'LC'
and D.Year = YEAR(GETDATE())-1 --- Last Year
) y on c.CustomerKey = y.CustomerKey
where c.CustomerKey = '157053'
group by c.CustomerKey, c.CustomerId, c.CustomerName, c.BranchId, y.IncomingOrderTypeId
),
--*********************************************************************************************************************************--
OrderTypeCY as(
SELECT
c.CustomerKey
,c.BranchId
,c.SalesRepKey
,c.CustomerId
,c.CustomerName
,ISNULL(SUM(y.[Sale_Revenue]), 0) as [Sale_Revenue_CY]
,ISNULL(SUM(y.[Sale_GrossMarginTotal]), 0) as [Sale_GrossMarginTotal_CY]
,y.IncomingOrderTypeId as IncomingOrderType_CY
FROM live.DimCustomer c
left join (SELECT s.CustomerKey,iot.IncomingOrderTypeid, s.[Sale_Revenue], s.[Sale_GrossMarginTotal] FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d
on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType iot on iot.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where s.ReportCurrencyId = 'LC'
and D.Year = YEAR(GETDATE()) --- Current Year
) y on c.CustomerKey = y.CustomerKey
where c.CustomerKey = '157053'
group by c.CustomerKey, c.CustomerId, c.CustomerName, c.BranchId, y.IncomingOrderTypeId, c.SalesRepKey
)
--*********************************************************************************************************************************--
SELECT
otly.BranchId,
rep.SalesRepId,
rep.SalesRepName,
otly.CustomerId,
otly.CustomerName,
otly.Sale_Revenue_LY,
otly.Sale_GrossMarginTotal_LY,
IncomingOrderType_LY,
otcy.Sale_Revenue_CY,
otcy.Sale_GrossMarginTotal_CY,
IncomingOrderType_CY
from OrderTypeUsedLY otly
left join OrderTypeCY otcy
on otly.CustomerKey = otcy.CustomerKey
join live.DimCustomer cus on cus.CustomerKey = otcy.CustomerKey
join live.DimSalesRep rep on rep.SalesRepKey = otcy.SalesRepKey
order by otcy.Sale_Revenue_CY desc, otly.Sale_Revenue_LY desc
,rep.SalesRepId
And here is the outer apply I tried:
outer apply (
SELECT top 1
iot.IncomingOrderTypeId,
Sale_Revenue
FROM [dwh01].[live].DimIncomingOrderType iot
where iot.IncomingOrderTypeKey = y.IncomingOrderTypeKey
order by Sale_Revenue desc) x
In the first select ( with OrderTypeUsed_LY ) I get this:
And I get the same in the second select, but with the values for current year.
The purpose of the report is to see the difference in the incoming order type most used (most profit made with it) for a customer last year and to see if he continues to use it this year, or uses another incoming order type this year.
Again I'm sorry for the bad explanation, I'm trying my best (I understand myself very well)
Here is the expected result:
Expected Result
I marked in red the last year part and in green the current year part.
If you change the subquery to:
SELECT
iot.IncomingOrderTypeKey,
MAX(Sale_Revenue)
FROM [dwh01].[live].DimIncomingOrderType iot
GROUP BY iot.IncomingOrderTypeKey
then you can JOIN (not APPLY) directly on IncomingOrderTypeKey AND Sale_Revenue.
Try this:
USE dwh01;
DECLARE #CustomerKey varchar(6) = '157053'
, #ReportCurrencyId varchar(2) = 'LC'
, #CurrentYear int = YEAR(GETDATE())
, #TargetYear int = YEAR(GETDATE())-1
;
WITH FactsTable AS
(
SELECT
s.CustomerKey
, i.IncomingOrderTypeid
, [Sale_Revenue] = ISNULL(s.[Sale_Revenue] , 0)
, [Sale_GrossMarginTotal] = ISNULL(s.[Sale_GrossMarginTotal], 0)
, d.[Year]
FROM [dwh01].[live].[FactSales] s
inner join live.DimDate d on d.DateId = s.PostingDateKey
inner join live.DimIncomingOrderType i on i.IncomingOrderTypeKey = s.IncomingOrderTypeKey
where
s.CustomerKey = #CustomerKey
and s.ReportCurrencyId = #ReportCurrencyId
)
, OrderTypeTable
(
SELECT
c.CustomerKey
, c.BranchId
, c.CustomerId
, c.CustomerName
, c.SalesRepKey
, IncomingOrderType_LY = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.IncomingOrderTypeId ELSE 0 END)
, [Sale_Revenue_LY] = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.[Sale_Revenue] ELSE 0 END)
, [Sale_GrossMarginTotal_LY] = SUM(CASE WHEN y.[Year] = #TargetYear THEN y.[Sale_GrossMarginTotal] ELSE 0 END)
, IncomingOrderType_LY = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.IncomingOrderTypeId ELSE 0 END)
, [Sale_Revenue_CY] = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.[Sale_Revenue] ELSE 0 END)
, [Sale_GrossMarginTotal_CY] = SUM(CASE WHEN y.[Year] = #CurrentYear THEN y.[Sale_GrossMarginTotal] ELSE 0 END)
FROM live.DimCustomer c
left join FactsTable y on y.CustomerKey = c.CustomerKey
group by
c.CustomerKey
, c.BranchId
, c.CustomerId
, c.CustomerName
, y.IncomingOrderTypeId
, c.SalesRepKey
)
SELECT
O.BranchId
, R.SalesRepId
, R.SalesRepName
, O.CustomerId
, O.CustomerName
, O.Sale_Revenue_LY
, O.Sale_GrossMarginTotal_LY
, O.IncomingOrderType_LY
, O.Sale_Revenue_CY
, O..Sale_GrossMarginTotal_CY
, O.IncomingOrderType_CY
from OrderTypeTable O
join live.DimSalesRep R on R.SalesRepKey = O.SalesRepKey
order by
O.Sale_Revenue_CY desc
, O.Sale_Revenue_LY desc
, R.SalesRepId
The solution is with using row_number() function in the inner query of the first CTE:
(
select *, row_number() over (partition by x0.CustomerKey order by x0.Sale_Revenue desc) as rn
from
(
select fs.CustomerKey, iot.IncomingOrderTypeKey,
sum(fs.Sale_Revenue) as Sale_Revenue
FROM [dwh01].[live].DimIncomingOrderType iot
join live.FactSales fs
on iot.IncomingOrderTypeKey = fs.IncomingOrderTypeKey
join live.DimDate d
on d.DateId = fs.PostingDateKey
where d.[year] = #CurrentYear
GROUP BY fs.CustomerKey, iot.IncomingOrderTypeKey
) as x0
) as x1 on x1.CustomerKey = s.CustomerKey
The row_number() function gets only the first row from the result for each customer, and that is with the biggest sale revenue ( order by sale_revenue desc).

sccm query cross apply outerapply doesnt give output

iam running SQL query which has cross apply and outer apply , i need state names as complaint , non complaint and pending system restart, but data iam getting is for all assignment id , please find query
SELECT cia.Assignment_UniqueID
, cia.AssignmentID
, cia.AssignmentName
, cia.EnforcementDeadline
, cia.StartTime
, sn.StateName
, NumberOfComputers = sc.StateCount
, Tot.TotalClientPerAssignment
, DeploymentStateID=sc.StateType*10000 + sc.StateID
, PComputers = cast(sc.StateCount * 100.00 / isnull(NULLIF (Tot.TotalClientPerAssignment, 0), 1) AS decimal(5, 2))
FROM v_CIAssignment cia
CROSS apply
(SELECT StateType, StateID, StateCount = count(*)
FROM v_AssignmentState_Combined
WHERE AssignmentID = cia.AssignmentID AND StateType IN (300, 301)
GROUP BY StateType, StateID) sc
CROSS apply
(SELECT DISTINCT TotalClientPerAssignment = count(atm.ResourceID) OVER (partition BY atm.assignmentid)
FROM v_CIAssignmentTargetedMachines atm
WHERE atm.AssignmentID = cia.AssignmentID) Tot
LEFT JOIN v_StateNames sn ON sn.TopicType = sc.StateType AND sn.StateID = sc.StateID
WHERE cia.AssignmentID = 2238
-- and sn.statename like '%Compliant%' or sn.statename like '%Pending system restart%'
and sn.statename like '%Compliant%' and sn.statename like '%restart%'
ORDER BY cia.AssignmentID, sc.StateCount DESC, sn.StateName
output iam getting is as follows
i need only statename as complaint , non complaint and pending restart for assignment id 2238 only but iam getting data for all assignment id
can you please help
output of query
This is because of your left join that's doesn't have any assignmentID
LEFT JOIN v_StateNames sn ON sn.TopicType = sc.StateType AND sn.StateID = sc.StateID
I suggest to use following query.
SELECT cia.Assignment_UniqueID
, cia.AssignmentID
, cia.AssignmentName
, cia.EnforcementDeadline
, cia.StartTime
, (SELECT StateName FROM v_StateNames WHERE TopicType = sc.StateType AND StateID = sc.StateID and statename like '%Compliant%' and statename like '%restart%') as StateName
, NumberOfComputers = sc.StateCount
, Tot.TotalClientPerAssignment
, DeploymentStateID=sc.StateType*10000 + sc.StateID
, PComputers = cast(sc.StateCount * 100.00 / isnull(NULLIF (Tot.TotalClientPerAssignment, 0), 1) AS decimal(5, 2))
FROM v_CIAssignment cia
CROSS apply
(SELECT StateType, StateID, StateCount = count(*)
FROM v_AssignmentState_Combined
WHERE AssignmentID = cia.AssignmentID AND StateType IN (300, 301)
GROUP BY StateType, StateID) sc
CROSS apply
(SELECT DISTINCT TotalClientPerAssignment = count(atm.ResourceID) OVER (partition BY atm.assignmentid)
FROM v_CIAssignmentTargetedMachines atm
WHERE atm.AssignmentID = cia.AssignmentID) Tot
WHERE cia.AssignmentID = 2238
ORDER BY cia.AssignmentID, sc.StateCount DESC

This SQL query is taking too long

This SQL query is taking too long
SELECT
s.State
, ServiceCenter
, s.LocationId
, LMG.dbo.ProperCase(LastName + ', ' + FirstName + ' (' + convert(varchar,s.ClientId) + ')') as Client
, ISNULL(ul.ContractorName, ServiceCenter) as ContractorName
, InvoiceId as InvoiceNumber
, s.ItemDescription
, s.Quantity
--, s.Revenue
--, SUM(s.Quantity) as Quantity
, SUM(s.Quantity * s.UnitPrice) as Revenue
--, SUM(s.Quantity * s.Revenue) as Total
, SUM(Quantity * lxref.Amount) as ContractorPayment
, (SELECT InvoiceAmount FROM AG1.MAMOZI.dbo.tInvoices i WHERE s.InvoiceId = i.invoiceId AND DeletedStatus IS NULL) as InvoiceAmount
, (SELECT SUM(Payment) FROM AG1.MAMOZI.dbo.tPayments p WHERE s.InvoiceId = p.invoiceId AND DeletedStatus IS NULL) as PaymentAmount
, (SELECT PaymentType FROM #PaymentTypeGuardian pt WHERE pt.ClientId = s.ClientId AND pt.InvoiceId = s.InvoiceId) as PaymentType
, ISNULL((SELECT SUM(AccountBalance) FROM [PLUSREPORT].Warehouse_LMG1.dbo.RptAccountBalance a WHERE a.CompanyId = 3 AND a.ClientId = CAST(s.ClientId as varchar(max))), 0) as AccountBalance
FROM #ServicePaymentGuardian s
INNER JOIN AG1.MAMOZI.dbo.tClient c on s.ClientId = c.ClientId
INNER JOIN DATABASESAVE.MAMO.org.LocationExtended le on s.LocationID = le.OrgDatabaseid
INNER JOIN DATABASESAVE.MAMO.jur.Location ul on le.LocationId = ul.LocationId AND ul.LocationTypeid = 2
INNER JOIN DATABASESAVE.MAMO.base.Jurisdiction uj on ul.JurisdictionId = uj.JurisdictionId AND uj.CompanyId = 3
INNER JOIN DATABASESAVE.MAMO.jur.LocationServicePaymentXref lxref on ul.LocationId = lxref.LocationId and s.ServicePaymentId = lxref.ServicePaymentId
GROUP BY
s.State
, ServiceCenter
, s.LocationId
, s.ClientId
, c.LastName
, c.FirstName
, s.InvoiceId
, s.Quantity
, s.ItemDescription
, s.ServicePaymentId
, ul.ContractorName
Order by State, ServiceCenter, InvoiceNumber, LastName, FirstName, ItemDescription
see execution plan - maybe you need to add indexes
run query without sub-queries and see how long it will take then
try to split query to smaller parts (and run it separately) to find out which part slows query down

sql sum() causing doubling of values with left outer join

The left out join on dbo.SalespersonProject is causing the value for TranAmt to double. I need to sum the legit TranAmt for projects, but adding in the left outer join and SalesPerson02, causes a match an incorrect doubling.
SELECT ARDoc.SlsperId AR_Doc_Sls_ID
, CASE
WHEN ARTran.TranType = 'CM' THEN SUM(ARTran.TranAmt) * -1
ELSE SUM(ARTran.TranAmt)
END TranAmt
, MAX(CASE
WHEN SalesCommOrder = 1 THEN SalesPersonId
END) Salesperson01
, MAX(ISNULL(CASE
WHEN SalesCommOrder = 1 THEN Percentage
END, .03)) Commission01
, MAX(CASE
WHEN SalesCommOrder = 2 THEN SalesPersonId
END) Salesperson02
, MAX(CASE
WHEN SalesCommOrder = 2 THEN Percentage
END) Commission02
, PJPROJ.project PJ_ID
, PJPROJ.project_desc PJ_Description
, PJPROJ.slsperid SME
, ARDoc.CustId Cust_ID
, CASE
WHEN RTRIM(ARTran.InvtId) = 'GRAPHICS' THEN 1
WHEN RTRIM(ARTran.InvtID) = 'SERVICE CONTRACT' THEN 2
END InvtID
, RTRIM(ARDoc.CustId) + ' ' + Customer.BillName Cust_ID_Name
, CONVERT( DATE, ARTran.TranDate, 101) Doc_Date
, ARTran.TranType Doc_Type
, ARTran.RefNbr
, PJPROJ.start_date
, SUM(ARTran.ExtCost) ExtCost
, SUM(ARTran.UnitPrice) UnitPrice
, SUM(ARTran.Qty) Qty
, (
SELECT SUM(b.eac_amount) [Budg Rev]
FROM pjptdsum b
INNER JOIN pjacct a ON a.acct = b.acct
AND a.acct_type = 'RV'
WHERE ARDoc.ProjectID = b.project) Budget_Rev
, (
SELECT SUM(b.eac_amount) [Budg Rev]
FROM pjptdsum b
INNER JOIN pjacct a ON a.acct = b.acct
AND a.acct_type = 'EX'
WHERE ARDoc.ProjectID = b.project) Budget_EAC
, so.TotMerch SalesOrderTotal
, Salesperson.Name
, ARTran.PerPost
, PJPROJ.manager2
, PJEMPLOY.emp_name
FROM Testnewgroundapp.dbo.ARDoc ARDoc
INNER JOIN Testnewgroundapp.dbo.ARTran ARTran ON ARDoc.CustId = ARTran.CustId
AND ARDoc.RefNbr = ARTran.RefNbr
AND ARDoc.DocType = ARTran.TranType
INNER JOIN Testnewgroundapp.dbo.Customer Customer ON ARDoc.CustId = Customer.CustId --INNER JOIN #CustomerTab ct
LEFT OUTER JOIN Testnewgroundapp.dbo.Salesperson Salesperson ON ARDoc.SlsperId = Salesperson.SlsperId
LEFT OUTER JOIN Testnewgroundapp.dbo.PJPROJ PJPROJ ON ARDoc.ProjectID = PJPROJ.project
LEFT OUTER JOIN Testnewgroundapp.dbo.PJEMPLOY PJEMPLOY ON PJPROJ.manager2 = PJEMPLOY.employee
LEFT OUTER JOIN (
SELECT h.PerPost
, h.SlsperID
, SUM(h.TotMerch) TotMerch
FROM SOShipHeader H
GROUP BY h.PerPost
, h.SlsperID) so ON ARTran.PerPost = so.PerPost
AND ARDoc.SlsperId = so.SlsperID
LEFT OUTER JOIN TestCommissions.dbo.SalespersonProject SalespersonProject ON SalespersonProject.ProjectId = PJPROJ.project --AND SalespersonProject.SalesPerson_Id = #ApplicationUserID
LEFT OUTER JOIN TestCommissions.dbo.SalesPerson AppSalesPerson ON AppSalesPerson.Id = SalespersonProject.SalesPerson_Id
WHERE
(ARTran.TranType = 'CM'
AND ARTran.DrCr = 'D'
OR ARTran.DrCr = 'C'
AND
(ARTran.TranType = 'CS'
OR ARTran.TranType = 'DM'
OR ARTran.TranType = 'IN'
)
)
AND ARTran.TaskID NOT LIKE '%60850'
AND ARTRan.TaskID NOT LIKE '%60900'
AND ARTran.invtid <> 'TSCINC001'
AND ARTran.TranClass NOT IN ('F', 'N', 'T')
AND ARTran.Acct NOT IN ('2590', '2040', '2037')
AND CONVERT(INT, ARTran.Acct) > 1301
AND CONVERT(INT, ARTran.PerPost) BETWEEN 201504 AND 201504
AND ARTran.Rlsed = 1
AND PJPROJ.project IS NOT NULL
AND artran.cpnyid IN ('R', 'A')
GROUP BY ARDoc.SlsperId
, ARDoc.ProjectID
, PJPROJ.project
, PJPROJ.project_desc
, PJPROJ.slsperid
, ARDoc.CustId
, ARTran.InvtId
, Customer.BillName
, ARTran.TranDate
, ARTran.TranType
, ARTran.RefNbr
, PJPROJ.start_date
, so.TotMerch
, Salesperson.Name
, ARTran.PerPost
, ARDoc.CpnyID
, PJPROJ.manager2
, PJEMPLOY.emp_name
HAVING ARDoc.SlsperId = 'bpettit'
ORDER BY ARDoc.SlsperId, ARTran.PerPost, PJPROJ.project
If an extra joined table has two records per one main record, this makes each main record appear twice in the result set. The following grouping and summing will then sum each value of the main record or another joined table twice.
Temporarily remove the grouping and summing, but keep all the joins and look at the result set. You will then probably see what causes this doubling.