Search code examples
sqlvolusion

SQL - Error "Opening Recordset"


Making an SQL export for Volusion and getting an error that causes a freeze on "Step 2 of 3 - Opening Recordset".

SELECT 
    od.ProductCode
    , SUM(od.Quantity) AS 'Total Units Sold'
    , SUM(od.TotalPrice) AS 'Total Payment Received'
    , SUM(ISNULL(od.Vendor_Price, 0) * od.Quantity) AS 'Total Cost'
    , SUM(od.TotalPrice) / SUM(od.Quantity) AS 'Average Price'
    , ((SUM(od.TotalPrice) - SUM(ISNULL(od.Vendor_Price, 0) * od.Quantity)) / SUM(od.TotalPrice)) AS 'Average Margin'
FROM OrderDetails AS od
LEFT JOIN Orders AS o
    ON o.OrderID = od.OrderID
LEFT JOIN Customers AS c 
    ON c.CustomerID = o.CustomerID
WHERE c.CustomerID >= 23
    AND c.CustomerID <> 24
    AND o.Orderstatus <> 'cancelled'
    AND c.AccessKey <> 'A'
    AND o.OrderDate BETWEEN '2/28/2015 0:00' AND '5/28/2015 23:59'
    AND o.Orderstatus NOT LIKE '%Returned'
GROUP BY 
    od.ProductCode
ORDER BY SUM(od.Quantity) DESC

Completely perplexed, but I have identified the line causing the issue:

, ((SUM(od.TotalPrice) - SUM(ISNULL(od.Vendor_Price, 0) * od.Quantity)) / SUM(od.TotalPrice)) AS 'Average Margin'

If that line is removed it will return fine.

Any help is appreciated.

Thanks,

Edit: There are a lot of columns in OrderDetails, but the three in question would be:

Quantity, Vendor_Price, TotalPrice


Solution

  • There is no syntax error in your query. As you said the error is coming in

    , ((SUM(od.TotalPrice) - SUM(ISNULL(od.Vendor_Price, 0) * od.Quantity)) 
               / SUM(od.TotalPrice)) AS 'Average Margin'
    

    only two possibilities there

    1. Column name misspelled. But all the above mentioned columns are used earlier columns also. So its fine

    2. The next issue can be division is happening here.Division by zero can be an issue. Check Sum(od.TotalPrice) is non-zero always..