SQL SUM columns from different tables - sql

Good Afternoon,
I currently have the query:
SELECT erp_user.login,
SUM(invoice_header.invoice_amount) as 'Invoices Billed'
FROM erp_user
LEFT JOIN order_header ON erp_user.erp_user_id = order_header.req_by
LEFT JOIN invoice_instruct_header ON order_header.order_id = invoice_instruct_header.order_id
LEFT JOIN invoice_header ON invoice_instruct_header.instruct_id = invoice_header.instruct_no
WHERE erp_user.supervisor_id IS NOT NULL AND user_id_type = 'I' AND erp_user.company_id IS NOT NULL AND erp_user.is_active = 1
GROUP BY erp_user.login
It gives me a list of total billing in our system by employee where the employee is signed to a job on the job header.
I would love to add the total amount of open PO's to this query so I added:
SELECT erp_user.login, SUM(invoice_header.invoice_amount) as 'Invoices Billed', sum(po_header.po_amount) AS "Open PO's"
FROM erp_user
LEFT JOIN order_header ON erp_user.erp_user_id = order_header.req_by
LEFT JOIN invoice_instruct_header ON order_header.order_id = invoice_instruct_header.order_id
LEFT JOIN invoice_header ON invoice_instruct_header.instruct_id = invoice_header.instruct_no
LEFT JOIN po_header ON order_header.order_id = po_header.order_id
WHERE erp_user.supervisor_id IS NOT NULL AND user_id_type = 'I' AND erp_user.company_id IS NOT NULL AND erp_user.is_active = 1 AND po_header.status = 1
GROUP BY erp_user.login
ORDER BY "Open PO's"
That query gives me numbers in my Open PO's column, but they are incorrect and I'm at the point now where I can't figure out how to troubleshoot this.
Can someone please point me in the right direction? I don't mind doing the work, just need a pointer. Thanks!

Please be aware of conbination of Left join and Where clause.
SELECT erp_user.login
, SUM(invoice_header.invoice_amount) as 'Invoices Billed'
, sum(CASE WHEN po_header.status = 1 THEN po_header.po_amount ELSE 0 END) AS "Open PO's"
FROM erp_user
LEFT JOIN order_header ON erp_user.erp_user_id = order_header.req_by
LEFT JOIN invoice_instruct_header ON order_header.order_id = invoice_instruct_header.order_id
LEFT JOIN invoice_header ON invoice_instruct_header.instruct_id = invoice_header.instruct_no
LEFT JOIN po_header ON order_header.order_id = po_header.order_id
WHERE erp_user.supervisor_id IS NOT NULL
AND user_id_type = 'I'
AND erp_user.company_id IS NOT NULL
AND erp_user.is_active = 1
GROUP BY erp_user.login
ORDER BY "Open PO's";

If po_header joins to order_header, then in your original query it would be repeating each po_header for each invoice_header as well (leading to the incorrect calculation).
You could use outer apply() like so:
select
erp_user.login
, [Invoices Billed] = sum(invoice_header.invoice_amount)
, x.[Open POs]
from erp_user
left join order_header
on erp_user.erp_user_id = order_header.req_by
left join invoice_instruct_header
on order_header.order_id = invoice_instruct_header.order_id
left join invoice_header
on invoice_instruct_header.instruct_id = invoice_header.instruct_no
outer apply (
select
[Open POs] = sum(po_header.po_amount)
from po_header p
inner join order_header oh
on oh.order_id = p.order_id
where oh.req_by = erp_user.erp_user_id
) x
where erp_user.supervisor_id is not null
and erp_user.company_id is not null
and erp_user.is_active = 1
and user_id_type = 'I'
group by erp_user.login

Related

SQL - SUM TotalValue returning a null with LEFT JOIN Clause

I'd to like SUM a TotalValue column based on Vendor and logged in user. I completely returning a right value of other info in logged user and the connected vendor, the problem is the SUM of TotalValue column is returning a null value. am I missing something?
This is what I've already tried:
SELECT ,v.VendorName ,
u.Product ,
v.[Description] ,
v.Status ,
SUM(cpm.TotalValue) AS TotalValue
FROM Vendor v
LEFT JOIN [ProductContract] c ON v.VendorId = c.VendorId
AND c.[Status] = 4
AND c.ProductContractId IN
(SELECT con.ProductContractId
FROM [ProductContract] con
INNER JOIN [ProductContractPermission] cp ON cp.ProductContractId = con.ProductContractId
WHERE cp.UserInfoId = #UserInfoId)
LEFT JOIN ProductContractPaymentMenu cpm ON c.ProductContractId = cpm.ProductContractId
AND c.[Status] = 4
AND c.VendorId = #VendorId
LEFT JOIN VendorContact vc ON v.VendorId = vc.VendorId
AND vc.[Type] = 1
LEFT JOIN UserInfo u ON vc.UserInfoId = u.UserInfoId
WHERE v.VendorId IN
(SELECT VendorId
FROM ClientVendor
WHERE ClientId = #VendorId)
GROUP BY v.VendorName,
u.Product,
v.[Description],
v.Status,
cpm.TotalValue
ORDER BY v.[Status],
v.CreatedOn
Seems that you want to apply an aggregate filter, this is the famous HAVING clause:
...
GROUP BY v.VendorName,
u.Product,
v.[Description],
v.Status,
cpm.TotalValue
HAVING
SUM(cpm.TotalValue) > 0
ORDER BY v.[Status],
v.CreatedOn
Hi i think you have to add ISNULL(value,defaultvalue) because cpm table was on left join and it can be null.
SELECT v.VendorName ,
u.Product ,
v.[Description] ,
v.Status ,
SUM(ISNULL(cpm.TotalValue,0)) AS TotalValue
FROM Vendor v
LEFT JOIN [ProductContract] c ON v.VendorId = c.VendorId
AND c.[Status] = 4
AND c.ProductContractId IN
(SELECT con.ProductContractId
FROM [ProductContract] con
INNER JOIN [ProductContractPermission] cp ON cp.ProductContractId = con.ProductContractId
WHERE cp.UserInfoId = #UserInfoId)
LEFT JOIN ProductContractPaymentMenu cpm ON c.ProductContractId = cpm.ProductContractId
AND c.[Status] = 4
AND c.VendorId = #VendorId
LEFT JOIN VendorContact vc ON v.VendorId = vc.VendorId
AND vc.[Type] = 1
LEFT JOIN UserInfo u ON vc.UserInfoId = u.UserInfoId
WHERE v.VendorId IN
(SELECT VendorId
FROM ClientVendor
WHERE ClientId = #VendorId)
GROUP BY v.VendorName,
u.Product,
v.[Description],
v.Status,
cpm.TotalValue
ORDER BY v.[Status],
v.CreatedOn
https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql?view=sql-server-2017
Edit: other point you have miss ',' in your query after the SELECT.
Your left join on ProductContractPaymentMenu may not always get an item, so cpm.TotalValue can be NULL sometimes. When you use SUM and when one value is NULL then the result will be NULL. You might rewrite that part as:
SUM(ISNULL(cpm.TotalValue, 0)) AS TotalValue
In that case, it will treat non-existing records as value 0.

SQL - charges and payments in same column; how to break it out

I have a SQL query that is pulling data from multiple tables (I have 11 joins)
There is an "ARTransaction" table which contains charges, payments, adjustments, etc. and there is a "transactionCodeID" column inside of that which describes the type of transaction.
I am trying to select a lot of data, but need two separate columns(the ones with comments above them), one for charges and one for payments. Is there a way to achieve this without using the where clause? I tried to use a nested select statement but it returned the same value for every single row (the total amount)
I am attaching the query below - thanks in advance! Also I am fairly new to data retrieval so if anything else looks wonky any other advice is greatly appreciated.
SELECT CONVERT(varchar(10),sl.ServiceDtFrom, 101) AS 'srvdate'
, f.Alias AS 'svc dprtmnt'
, CASE WHEN pc.Alias IS NULL
THEN po.Name
ELSE pc.Description END AS 'svc dept grp'
, COUNT(clm.ID) AS 'clm cnt'
, COUNT(p.ID) AS 'ptnt count'
/* 1 */
, SUM(ar.Amount) AS 'all chgs' --ONLY CHARGES (tt.ID IN(1,2))
, SUM(sl.Units + sl.TimeUnits + sl.PhysicalStatusUnits) AS 'chg units sum'
/* 2 */
, SUM(ar.Amount) AS 'net pmt' --ONLY PAYMENTS (tt.ID IN(3,4,9,10,11,12,20,21))
FROM ARTransaction ar WITH (NOLOCK)
LEFT JOIN ServiceLine sl WITH (NOLOCK)
ON ar.ServiceLineID = sl.ID
LEFT JOIN Incident i WITH (NOLOCK)
ON sl.IncidentID = i.ID
LEFT JOIN HealthCareFacility f WITH (NOLOCK)
ON i.FacilityID = f.ID
LEFT JOIN ProvOrgFacility poc WITH (NOLOCK)
ON poc.FacilityID = f.ID
LEFT JOIN ProfitCenter pc WITH (NOLOCK)
ON poc.ProfitCenterID = pc.ID
LEFT JOIN ProviderOrganization po WITH (NOLOCK)
ON i.ProvOrgID = po.ID
LEFT JOIN Claim clm WITH (NOLOCK)
ON i.ID = clm.IncidentID
LEFT JOIN Person p WITH (NOLOCK)
ON i.PatientID = p.ID
LEFT JOIN TransactionCode tc WITH (NOLOCK)
ON ar.TransactionCodeID = tc.ID
LEFT JOIN TransactionType tt WITH (NOLOCK)
ON tc.TransactionTypeID = tt.ID
WHERE i.IsReversed <> 1
AND sl.ServiceDtFrom IS NOT NULL
GROUP BY
sl.ServiceDtFrom, f.Alias
, po.Name, pc.Alias, pc.Description
ORDER BY 1,3,2
You can use CASE statements to achieve this:-
SELECT CONVERT(varchar(10),sl.ServiceDtFrom, 101) AS 'srvdate'
, f.Alias AS 'svc dprtmnt'
, CASE WHEN pc.Alias IS NULL
THEN po.Name
ELSE pc.Description END AS 'svc dept grp'
, COUNT(clm.ID) AS 'clm cnt'
, COUNT(p.ID) AS 'ptnt count'
/* 1 */
, SUM(case when tt.ID IN(1,2) then ar.Amount else 0 end) AS 'all chgs' --ONLY CHARGES (tt.ID IN(1,2))
, SUM(sl.Units + sl.TimeUnits + sl.PhysicalStatusUnits) AS 'chg units sum'
/* 2 */
, SUM(case when tt.ID IN(3,4,9,10,11,12,20,21) then ar.Amount else 0 end) AS 'net pmt' --ONLY PAYMENTS (tt.ID IN(3,4,9,10,11,12,20,21))
FROM ARTransaction ar WITH (NOLOCK)
LEFT JOIN ServiceLine sl WITH (NOLOCK)
ON ar.ServiceLineID = sl.ID
LEFT JOIN Incident i WITH (NOLOCK)
ON sl.IncidentID = i.ID
LEFT JOIN HealthCareFacility f WITH (NOLOCK)
ON i.FacilityID = f.ID
LEFT JOIN ProvOrgFacility poc WITH (NOLOCK)
ON poc.FacilityID = f.ID
LEFT JOIN ProfitCenter pc WITH (NOLOCK)
ON poc.ProfitCenterID = pc.ID
LEFT JOIN ProviderOrganization po WITH (NOLOCK)
ON i.ProvOrgID = po.ID
LEFT JOIN Claim clm WITH (NOLOCK)
ON i.ID = clm.IncidentID
LEFT JOIN Person p WITH (NOLOCK)
ON i.PatientID = p.ID
LEFT JOIN TransactionCode tc WITH (NOLOCK)
ON ar.TransactionCodeID = tc.ID
LEFT JOIN TransactionType tt WITH (NOLOCK)
ON tc.TransactionTypeID = tt.ID
WHERE i.IsReversed <> 1
AND sl.ServiceDtFrom IS NOT NULL
GROUP BY

SQl Error : Each GROUP BY expression must contain at least one column that is not an outer reference [duplicate]

This question already has answers here:
Each GROUP BY expression must contain at least one column that is not an outer reference
(8 answers)
Closed 6 years ago.
I get this error
Each GROUP BY expression must contain at least one column that is not an outer reference
while running this query:
SELECT TOP 1
SUM(mla.total_current_attribute_value)
FROM
partstrack_machine_location_attributes mla (NOLOCK)
INNER JOIN
#tmpInstallParts_Temp installpartdetails ON mla.machine_sequence_id = installpartdetails.InstallKitToMachineSequenceId
AND (CASE WHEN mla.machine_side_id IS NULL THEN 1
WHEN mla.machine_side_id = installpartdetails.InstallKitToMachineSideId THEN 1 END
) = 1
INNER JOIN
partstrack_mes_attribute_mapping mam (NOLOCK) ON mla.mes_attribute = mam.mes_attribute_name
INNER JOIN
partstrack_attribute_type at (NOLOCK) ON mam.pt_attribute_id = at.pt_attribute_id
INNER JOIN
partstrack_ipp_mes_attributes ima(NOLOCK) ON at.pt_attribute_id = ima.pt_attribute_id
WHERE
mla.active_ind = 'Y' AND
ima.ipp_ID IN (SELECT ipp.ipp_id
FROM partstrack_individual_physical_part ipp
INNER JOIN #tmpInstallParts_Temp tmp ON (ipp.ipp_id = tmp.InstallingPartIPPId OR
(CASE WHEN tmp.InstallingPartIPKId = '-1' THEN 1 END) = 1
)
GROUP BY
ima.ipp_id
Can someone help me?
This is the text of the query from the first revision of the question.
In later revisions you removed the last closing bracket ) and the query became syntactically incorrect. You'd better check and fix the text of the question and format the text of the query, so it is readable.
SELECT TOP 1
SUM(mla.total_current_attribute_value)
FROM
partstrack_machine_location_attributes mla (NOLOCK)
INNER JOIN #tmpInstallParts_Temp installpartdetails
ON mla.machine_sequence_id = installpartdetails.InstallKitToMachineSequenceId
AND (CASE WHEN mla.machine_side_id IS NULL THEN 1
WHEN mla.machine_side_id = installpartdetails.InstallKitToMachineSideId THEN 1 END) = 1
INNER JOIN partstrack_mes_attribute_mapping mam (NOLOCK) ON mla.mes_attribute = mam.mes_attribute_name
INNER JOIN partstrack_attribute_type at (NOLOCK) ON mam.pt_attribute_id = at.pt_attribute_id
INNER JOIN partstrack_ipp_mes_attributes ima(NOLOCK) ON at.pt_attribute_id = ima.pt_attribute_id
WHERE
mla.active_ind = 'Y'
AND ima.ipp_ID IN
(
Select
ipp.ipp_id
FROM
partstrack_individual_physical_part ipp
INNER JOIN #tmpInstallParts_Temp tmp
ON (ipp.ipp_id = tmp.InstallingPartIPPId
OR (CASE WHEN tmp.InstallingPartIPKId = '-1' THEN 1 END) = 1)
GROUP BY
ima.ipp_id
)
With this formatting it is clear now that there is a subquery with GROUP BY.
Most likely it is just a typo: you meant to write GROUP BY ipp.ipp_id instead of GROUP BY ima.ipp_id.
If you really wanted to have the GROUP BY not in a subquery, but in the main SELECT, then you misplaced the closing bracket ) and the query should look like this:
SELECT TOP 1
SUM(mla.total_current_attribute_value)
FROM
partstrack_machine_location_attributes mla (NOLOCK)
INNER JOIN #tmpInstallParts_Temp installpartdetails
ON mla.machine_sequence_id = installpartdetails.InstallKitToMachineSequenceId
AND (CASE WHEN mla.machine_side_id IS NULL THEN 1
WHEN mla.machine_side_id = installpartdetails.InstallKitToMachineSideId THEN 1 END) = 1
INNER JOIN partstrack_mes_attribute_mapping mam (NOLOCK) ON mla.mes_attribute = mam.mes_attribute_name
INNER JOIN partstrack_attribute_type at (NOLOCK) ON mam.pt_attribute_id = at.pt_attribute_id
INNER JOIN partstrack_ipp_mes_attributes ima(NOLOCK) ON at.pt_attribute_id = ima.pt_attribute_id
WHERE
mla.active_ind = 'Y'
AND ima.ipp_ID IN
(
Select
ipp.ipp_id
FROM
partstrack_individual_physical_part ipp
INNER JOIN #tmpInstallParts_Temp tmp
ON (ipp.ipp_id = tmp.InstallingPartIPPId
OR (CASE WHEN tmp.InstallingPartIPKId = '-1' THEN 1 END) = 1)
)
GROUP BY
ima.ipp_id
In any case, proper formatting of the source code can really help.
Group By ima.ipp_id
should be applicable to outer query. Because of incorrect placement of '(' it was applying to inner query.
Now after correcting the query,it's working fine without any issues.
Final Query is :
SELECT TOP 1
SUM(mla.total_current_attribute_value)
FROM
partstrack_machine_location_attributes mla (NOLOCK)
INNER JOIN #tmpInstallParts_Temp installpartdetails
ON mla.machine_sequence_id = installpartdetails.InstallKitToMachineSequenceId
AND (CASE WHEN mla.machine_side_id IS NULL THEN 1
WHEN mla.machine_side_id = installpartdetails.InstallKitToMachineSideId THEN 1 END ) = 1
INNER JOIN partstrack_mes_attribute_mapping mam (NOLOCK) ON mla.mes_attribute = mam.mes_attribute_name
INNER JOIN partstrack_attribute_type at (NOLOCK) ON mam.pt_attribute_id = at.pt_attribute_id
INNER JOIN partstrack_ipp_mes_attributes ima(NOLOCK) ON at.pt_attribute_id = ima.pt_attribute_id
WHERE
mla.active_ind = 'Y'
AND ima.ipp_ID IN
(
Select
ipp.ipp_id
FROM
partstrack_individual_physical_part ipp
INNER JOIN #tmpInstallParts_Temp tmp
ON (ipp.ipp_id = tmp.InstallingPartIPPId
OR (CASE WHEN tmp.InstallingPartIPKId = '-1' THEN 1 END ) =1)
)
GROUP BY ima.ipp_id
Thank you all.

using a subquery as a column that's using another column in the 'where' clause

I probably messed that title up! So I have a column called "programID" and I want another column to tell me the most recent date an order was placed using the programID. I think I'd need a subcolumn but the problem is how do I use the row's programID so that it matches the programID for the same row?
DECLARE #ClientIDs varchar(4) = 6653;
DECLARE #ProgramStatus char(1) = 'Y'; -- Y, N, or R
SELECT
rcp.RCPID AS ProgramID
, rcp.RCPName AS Program
, rcp.RCPActive AS ProgramStatus
, aa.AACustomCardInternalReview AS VCCP
, aa.AAJobNo AS AAJobNo
, aas.AASName AS AAStatus
, rcp.RCPOpsApproved AS OpsApproved
, clt.CltID AS ClientID
, rcp.RCPSignatureRequired AS SignatureRequired
, st.STEnumValue AS DefaultShipType
, rcp.RCPShipMethodOverrideType AS ShipTypeOverride
,aa.AANetworkProgramID
,(Select max(cdconfirmationdate) from carddet where ) --can't figure this part out
FROM
RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN ClientRetailerMap crm WITH (NOLOCK)
ON crm.CRMRetailerID = rcp.RCPRetailerID
INNER JOIN Client clt WITH(NOLOCK)
ON clt.CltID = crm.CRMCltID
LEFT JOIN AssociationApproval aa WITH (NOLOCK)
ON aa.AARetailerID = rcp.RCPRetailerID
AND aa.AABin = rcp.RCPBin6
AND aa.AAFrontOfPlasticTemplateID = rcp.RCPFOCTemplateID
AND aa.AABackOfPlasticTemplateID = rcp.RCPBOCTemplateID
AND ISNULL(aa.AACardID, 0) = ISNULL(rcp.RCPDefaultPlasticCardID, 0)
-- AND LOWER(rcp.RCPName) NOT LIKE '%do not use%' -- Needed for AA Job Number 1594
LEFT JOIN AssociationApprovalStatus aas WITH (NOLOCK)
ON aas.AASID = aa.AAAssociationApprovalStatusID
LEFT JOIN OpenLoopAssociation ola WITH (NOLOCK)
ON ola.OLAID=rcp.RCPOLAID
LEFT JOIN ClientCardProgramMap ccpm WITH (NOLOCK)
ON ccpm.CCPMCardProgramID = rcp.RCPID
AND ccpm.CCPMClientID = clt.CltID
LEFT JOIN TippingModule tm WITH (NOLOCK)
ON tm.TMid = rcp.RCPTippingModuleID
LEFT JOIN GiftCardTemplate fgt WITH (NOLOCK)
ON fgt.gtid = rcp.RCPFOCTemplateID
AND fgt.GTPage='P'
LEFT JOIN GiftCardTemplate bgt WITH (NOLOCK)
ON bgt.gtid = rcp.RCPBOCTemplateID
AND bgt.GTPage='PB'
LEFT JOIN Card c WITH (NOLOCK)
ON c.CardID = rcp.RCPDefaultCarrierID
LEFT JOIN CardType ct WITH (NOLOCK)
ON ct.CTID = c.CardTypeID
LEFT JOIN RetailerCardProgramTCSheetMap rtm1 WITH (NOLOCK)
ON rtm1.RTMRCPID = rcp.RCPID
AND rtm1.RTMInsertOrder = 1
LEFT JOIN RetailerCardProgramTCSheetMap rtm2 WITH (NOLOCK)
ON rtm2.RTMRCPID = rcp.RCPID
AND rtm2.RTMInsertOrder = 2
LEFT JOIN RetailerCardProgramTCSheetMap rtm3 WITH (NOLOCK)
ON rtm3.RTMRCPID = rcp.RCPID
AND rtm3.RTMInsertOrder = 3
LEFT JOIN RetailerCardProgramTCSheetMap rtm4 WITH (NOLOCK)
ON rtm4.RTMRCPID = rcp.RCPID
AND rtm4.RTMInsertOrder = 4
LEFT JOIN TCSheet i1 WITH (NOLOCK)
ON i1.TCSID = rtm1.RTMTCSID
LEFT JOIN TCSheet i2 WITH (NOLOCK)
ON i2.TCSID = rtm2.RTMTCSID
LEFT JOIN TCSheet i3 WITH (NOLOCK)
ON i3.TCSID = rtm3.RTMTCSID
LEFT JOIN TCSheet i4 WITH (NOLOCK)
ON i4.TCSID = rtm4.RTMTCSID
LEFT JOIN ShipType st WITH (NOLOCK)
ON st.STId = rcp.RCPDefaultShipTypeID
WHERE
clt.CltID IN (#ClientIDs) -- 6653 and 6657.
AND rcp.RCPActive IN (#ProgramStatus)
ORDER BY
AAJobNo
, Program
You want to join with a nested select on the table carddet. I'm inferring that RCPID is the relationship between carddet and your main table RetainerCardProgram...
SELECT rcp.RCPID AS ProgramID,
date.MAXDATE AS MaxDate,
rest of your columns...
FROM RetailerCardProgram rcp WITH (NOLOCK)
INNER JOIN (
SELECT RCPID, MAX(cdconfirmationdate) as 'MAXDATE'
FROM carddet
GROUP BY RCPID
) date on date.RCPID = rcp.RCPID
rest of query...
You may want a left join if not all IDs have a date in carddet.
Obligatory addition: Also your use of NOLOCK is a bit terrifying. See http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/

SQL Server 2008 : FROM clause syntax error

My code returns a syntax error on L42 (the from clause). I've looked and looked and to me, the syntax looks correct for the FROM.
The top part of the code creates a temp table 'subproducts'. Then I want to pull data from DB tables & pull relevant details from the new temp table.
Any ideas?
drop table ##subproducts;
SELECT
F1.[OrderNo]
,F1.[OrderSeqNo]
,F1.[OrderLineNo]
,sum(F1.[LineCost]) as LineCost
,sum(F1.[NetCost]) as NetCost
,sum(F1.[OrderNet]) as OrderNet
INTO
##subproducts
FROM
[UFPData].[dbo].[SalesStats] F1
WHERE
F1.MainProd = 'S'
GROUP BY
F1.OrderNo, F1.OrderSeqNo, F1.OrderLineNo;
SELECT *
FROM SalesStats F1
LEFT OUTER JOIN ##subproducts F2 ON F1.OrderNo = F2.OrderNo
AND F1.OrderSeqNo = F2.Orderseqno
AND F1.OrderLineNo = F2.OrderLineNo
WHERE YEAR(InvDate) = 2015
AND MONTH(InvDate) = 5
AND CustNo = 100382
AND MainProd = 'Y';
SELECT
ContractInfo.CONTRNO,
ContractInfo.CONTRDESC,
repcode,
RepName,
PriceAgreement,
ordercycle,
SalesStats.CustNo,
Customer.CustName,
SalesStats.InvDate,
SalesStats.InvoiceNo,
salesstats.ProdCode,
Price as ContractPrice,
subproduct.LineCost as LineCost,
subproduct.NetCost as NetCost,
subproduct.OrderNet as OrderNet,
contractinfo.NETCOST as BidPrice,
contractinfo.NETCOST* SUM(quantity) as BidCost,
FROM
UFPData.dbo.SalesStats
RIGHT OUTER JOIN
##subproducts ON UFPData.dbo.SalesStats.ProdCode = ##subproducts.ProdCode,
UFPData.dbo.SalesStats
LEFT OUTER JOIN
UFPData.dbo.Customer ON UFPData.dbo.SalesStats.CustNo = UFPData.dbo.Customer.CustNo, UFPData.dbo.SalesStats
LEFT OUTER JOIN
Pricing.dbo.InvManCen ON UFPData.dbo.SalesStats.ProdCode = Pricing.dbo.invmancen.UFPCODE, UFPData.dbo.SalesStats
RIGHT OUTER JOIN
UFPData.dbo.ContractInfo ON UFPData.dbo.Customer.CustNo = UFPData.dbo.ContractInfo.CUSTNO
AND UFPData.dbo.salesstats.prodcode = UFPData.dbo.contractinfo.prodcode,
WHERE
invdate BETWEEN '2015-05-01' and '2015-05-31'
AND TeamCode IN ('tm1','tm2','tm3')
AND ContractInfo.CONTRNO IN ('1500','1502','1503','1504','1505','1506','701','702','703','705','141',
'712', '713', '714', '715', '716', '717', '718', '719', '730', '731', '732') or CONTRNO between '3000' and '3049')
--and left(ordercycle,1) <> 'c'
GROUP BY
ContractInfo.CONTRNO,
repcode,
RepName,
SalesStats.CustNo,
Customer.CustName,
SalesStats.InvDate,
salesstats.ProdCode,
Price,
contractinfo.NETCOST,
SalesStats.InvoiceNo,
InvManCen.PS98,
ContractInfo.CONTRDESC,
ordercycle,
PriceAgreement,
case
when invdate > ('20' + LEFT(ENDDATE,2)+ '-'+ SUBSTRING(cast(ENDDATE as varchar(6)),3,2)+ '-'+ SUBSTRING(cast(ENDDATE as varchar(6)),5,2)) then 'Expired' else 'Live' end;
Many thanks in advance
This doesn't look right to me:
FROM
UFPData.dbo.SalesStats right outer join ##subproducts on UFPData.dbo.SalesStats.ProdCode = ##subproducts.ProdCode,
UFPData.dbo.SalesStats left outer join UFPData.dbo.Customer on UFPData.dbo.SalesStats.CustNo = UFPData.dbo.Customer.CustNo,
UFPData.dbo.SalesStats left outer join Pricing.dbo.InvManCen on UFPData.dbo.SalesStats.ProdCode = Pricing.dbo.invmancen.UFPCODE,
UFPData.dbo.SalesStats right outer join UFPData.dbo.ContractInfo on UFPData.dbo.Customer.CustNo = UFPData.dbo.ContractInfo.CUSTNO and UFPData.dbo.salesstats.prodcode = UFPData.dbo.contractinfo.prodcode,
Usually the format is something like this:
FROM
TableName
INNER JOIN SomeOtherTable...
INNER JOIN AnotherTable...
Note that the first table is mentioned once, not before every join. You also seem to have errant commas after each join, which isn't syntactically correct. I think you want this:
FROM
UFPData.dbo.SalesStats
right outer join ##subproducts on UFPData.dbo.SalesStats.ProdCode = ##subproducts.ProdCode
left outer join UFPData.dbo.Customer on UFPData.dbo.SalesStats.CustNo = UFPData.dbo.Customer.CustNo
left outer join Pricing.dbo.InvManCen on UFPData.dbo.SalesStats.ProdCode = Pricing.dbo.invmancen.UFPCODE
right outer join UFPData.dbo.ContractInfo on UFPData.dbo.Customer.CustNo = UFPData.dbo.ContractInfo.CUSTNO and UFPData.dbo.salesstats.prodcode = UFPData.dbo.contractinfo.prodcode
There could very well be more syntax errors throughout your query. I recommend formatting the code a little more cleanly to more easily find them. For example, contrast the above with something like this:
FROM
UFPData.dbo.SalesStats
RIGHT OUTER JOIN ##subproducts
ON UFPData.dbo.SalesStats.ProdCode = ##subproducts.ProdCode
LEFT OUTER JOIN UFPData.dbo.Customer
ON UFPData.dbo.SalesStats.CustNo = UFPData.dbo.Customer.CustNo
LEFT OUTER JOIN Pricing.dbo.InvManCen
ON UFPData.dbo.SalesStats.ProdCode = Pricing.dbo.invmancen.UFPCODE
RIGHT OUTER JOIN UFPData.dbo.ContractInfo
ON UFPData.dbo.Customer.CustNo = UFPData.dbo.ContractInfo.CUSTNO
AND UFPData.dbo.salesstats.prodcode = UFPData.dbo.contractinfo.prodcode
It's a small change, and often a matter of personal preference, but well formatted code brings about a number of advantages. Less horizontal scrolling makes it easier to see the relevant code in a single glance, line breaks for specific keywords and clauses makes it easier to spot errant commas, etc.
Here's what I think should be valid syntax for what you've provided, please try it and compare it to the original as there were multiple errors:
DROP TABLE ##subproducts;
SELECT F1.[OrderNo] ,
F1.[OrderSeqNo] ,
F1.[OrderLineNo] ,
SUM(F1.[LineCost]) AS LineCost ,
SUM(F1.[NetCost]) AS NetCost ,
SUM(F1.[OrderNet]) AS OrderNet
INTO ##subproducts
FROM [UFPData].[dbo].[SalesStats] F1
WHERE F1.MainProd = 'S'
GROUP BY F1.OrderNo ,
F1.OrderSeqNo ,
F1.OrderLineNo;
SELECT *
FROM SalesStats F1
LEFT OUTER JOIN ##subproducts F2 ON F1.OrderNo = F2.OrderNo
AND F1.OrderSeqNo = F2.Orderseqno
AND F1.OrderLineNo = F2.OrderLineNo
WHERE YEAR(InvDate) = 2015
AND MONTH(InvDate) = 5
AND CustNo = 100382
AND MainProd = 'Y';
SELECT ContractInfo.CONTRNO ,
ContractInfo.CONTRDESC ,
repcode ,
RepName ,
PriceAgreement ,
ordercycle ,
SalesStats.CustNo ,
Customer.CustName ,
SalesStats.InvDate ,
SalesStats.InvoiceNo ,
SalesStats.ProdCode ,
Price AS ContractPrice ,
subproduct.LineCost AS LineCost ,
subproduct.NetCost AS NetCost ,
subproduct.OrderNet AS OrderNet ,
ContractInfo.NetCost AS BidPrice ,
ContractInfo.NetCost * SUM(quantity) AS BidCost
FROM UFPData.dbo.SalesStats
RIGHT OUTER JOIN ##subproducts ON UFPData.dbo.SalesStats.ProdCode = ##subproducts.ProdCode
LEFT OUTER JOIN UFPData.dbo.Customer ON UFPData.dbo.SalesStats.CustNo = UFPData.dbo.Customer.CustNo
LEFT OUTER JOIN Pricing.dbo.InvManCen ON UFPData.dbo.SalesStats.ProdCode = Pricing.dbo.invmancen.UFPCODE
RIGHT OUTER JOIN UFPData.dbo.ContractInfo ON UFPData.dbo.Customer.CustNo = UFPData.dbo.ContractInfo.CUSTNO
AND UFPData.dbo.salesstats.prodcode = UFPData.dbo.contractinfo.prodcode
WHERE invdate BETWEEN '2015-05-01' AND '2015-05-31'
AND TeamCode IN ( 'tm1', 'tm2', 'tm3' )
AND (ContractInfo.CONTRNO IN ( '1500', '1502', '1503', '1504', '1505',
'1506', '701', '702', '703', '705',
'141', '712', '713', '714', '715', '716',
'717', '718', '719', '730', '731', '732' )
OR CONTRNO BETWEEN '3000' AND '3049')
GROUP BY ContractInfo.CONTRNO ,
repcode ,
RepName ,
SalesStats.CustNo ,
Customer.CustName ,
SalesStats.InvDate ,
SalesStats.ProdCode ,
Price ,
ContractInfo.NetCost ,
SalesStats.InvoiceNo ,
InvManCen.PS98 ,
ContractInfo.CONTRDESC ,
ordercycle ,
PriceAgreement ,
CASE WHEN invdate > ( '20' + LEFT(ENDDATE, 2) + '-'
+ SUBSTRING(CAST(ENDDATE AS VARCHAR(6)), 3, 2)
+ '-' + SUBSTRING(CAST(ENDDATE AS VARCHAR(6)), 5,
2) ) THEN 'Expired'
ELSE 'Live'
END;