
March 9th, 2013, 03:27 PM
|
|
Registered User
|
|
Join Date: Jun 2012
Posts: 15
Time spent in forums: 2 h 56 m 48 sec
Reputation Power: 0
|
|
Just posting the solution in case anybody's interested. Help from another forum. Derived tables were the answer. Very neat solution.
Code:
SELECT dbo.Customer.CustomerCode, dbo.SalesProposal.SPNo + ' (' + dbo.Forest.Forest + ')' AS SalesProposal, dbo.SalesProposal.SalesProposalID,
dbo.SalesProposal.PreDispatchInvoicing, CASE WHEN dbo.SalesProposal.PreDispatchInvoicing = 1 THEN 'Pre Dispatch' ELSE 'Post Dispatch' END AS Invoicing,
Invoice_Derived.InvoicedQuantity AS InvoicedQuantity, Dispatch_Derived.DeliveredQuantity AS DeliveredQuantity,
CASE WHEN dbo.SalesProposal.PreDispatchInvoicing = 1 THEN dbo.SalesProposal.ForecastQuantity - Invoice_Derived.InvoicedQuantity ELSE Dispatch_Derived.DeliveredQuantity
- Invoice_Derived.InvoicedQuantity END AS InvoiceableQuantity
FROM dbo.SalesProposal INNER JOIN
dbo.SalesProposalStatus ON dbo.SalesProposal.StatusID = dbo.SalesProposalStatus.SalesProposalStatusID AND
dbo.SalesProposalStatus.SalesProposalStatus = 'Sold' INNER JOIN
dbo.Forest ON dbo.SalesProposal.ForestID = dbo.Forest.ForestID INNER JOIN
dbo.Customer ON dbo.SalesProposal.CustomerID = dbo.Customer.CustomerID LEFT OUTER JOIN
(SELECT dbo.Invoice.SalesProposalID, SUM(dbo.InvoiceItem.Quantity) AS InvoicedQuantity
FROM dbo.Invoice INNER JOIN
dbo.InvoiceItem ON dbo.Invoice.InvoiceID = dbo.InvoiceItem.InvoiceID
GROUP BY dbo.Invoice.SalesProposalID) AS Invoice_Derived ON dbo.SalesProposal.SalesProposalID = Invoice_Derived.SalesProposalID LEFT OUTER JOIN
(SELECT SalesProposalID, SUM(Weight * ConversionFactor) AS DeliveredQuantity
FROM dbo.Dispatch
GROUP BY SalesProposalID) AS Dispatch_Derived ON Dispatch_Derived.SalesProposalID = dbo.SalesProposal.SalesProposalID
|