November 12, 2008 at 8:05 am
I am trying to create a SQL Script to pull data from three tables
Accounts (list of Customers),Sales (Invoice Tables),Sales_Payments (table with holds payments made against invoices) to display Customer AccountNumber,CustomerName, InvoiceBalance (for 0 - 14 days),InvoiceBalance (for 14-30 days).
I dont think I am getting the subtractio part correctly for each accountID .... any thoughts to correct this query..?
SELECT Accounts.AccountNumber,Accounts.CustomerName,
(SELECT SUM(ISNULL(Sales.subtotal,0) + ISNULL(Sales.vat,0))
- (SELECT SUM(ISNULL(Sales_Payments.Amount,0)) from Sales_Payments)
FROM Sales INNER JOIN Sales_Payments ON Sales.SaleID = Sales_Payments.SaleID
WHERE datediff(dd,Sales.dateandtime,getdate()) <= 14 AND Sales.Type = 'Invoice' AND
Sales.AccountID = Accounts.AccountID) AS [InvoiceBalance(0-14 Days)]
,
(SELECT SUM(ISNULL(Sales.subtotal,0) + ISNULL(Sales.vat,0))
- (SELECT SUM(ISNULL(Sales_Payments.Amount,0)) from Sales_Payments)
FROM Sales INNER JOIN Sales_Payments ON Sales.SaleID = Sales_Payments.SaleID
WHERE datediff(dd,Sales.dateandtime,getdate()) >= 15 AND
datediff(dd,Sales.dateandtime,getdate()) <= 31 AND
Sales.Type = 'Invoice' AND Sales.AccountID = Accounts.AccountID) AS [InvoiceBalance(15-31 Days)]
from Accounts INNER JOIN Sales ON Accounts.AccountID = Sales.AccountId
GROUP BY Accounts.AccountNumber,Accounts.CustomerName, Accounts.AccountID
November 12, 2008 at 9:01 am
Maybe something like:
SELECT A.AccountNumber
    ,A.CustomerName
    ,D.subtotal14 + D.vat14 - D.Payment14 AS [InvoiceBalance(0-14 Days)]
    ,D.subtotal31 + D.vat31 - D.Payment31 AS [InvoiceBalance(15-31 Days)]
FROM Accounts A
    JOIN
    (
        SELECT S.AccountID
            ,ISNULL(SUM(CASE WHEN S.dateandtime >= DT.DT14 THEN S.subtotal END), 0) AS subtotal14
            ,ISNULL(SUM(CASE WHEN S.dateandtime < DT.DT14 THEN S.subtotal END), 0) AS subtotal31
            ,ISNULL(SUM(CASE WHEN S.dateandtime >= DT.DT14 THEN S.vat END), 0) AS vat14
            ,ISNULL(SUM(CASE WHEN S.dateandtime < DT.DT14 THEN S.vat END), 0) AS vat31
            ,ISNULL(SUM(CASE WHEN S.dateandtime >= DT.DT14 THEN P.Amount END), 0) AS Payment14
            ,ISNULL(SUM(CASE WHEN S.dateandtime < DT.DT14 THEN P.Amount END), 0) AS Payment31
        FROM Sales S
            CROSS JOIN
            (
                SELECT DATEADD(d, -14, DATEDIFF(d, 0, GETDATE())) AS DT14
            ) DT
            LEFT JOIN Sales_Payments P
                ON S.SaleID = P.SaleID
        WHERE S.[Type] = 'Invoice'
            AND S.dateandtime >= DATEADD(d, -31, DATEDIFF(d, 0, GETDATE()))
        GROUP BY S.AccountID
    ) D
        ON A.AccountID = D.AccountID
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply