This is my first attempt at a Union and I am trying to sort a query by orderID and then the last line will show the orderID Total. I am not sure why, but my SUM does not appear to be working right. Could one of you seasoned veterans do me justice and help me understand what is right and what is wrong with my query. I appreciate any help you could offer.
Here is my Query:
SELECT
CAST(Orders.OrderID AS VARCHAR),
Orders.ShipCompanyName,
Orders.ShipFirstName,
Orders.ShipLastName,
Orders.Shipaddress1,
Orders.ShipAddress2,
Orders.ShipCity,
Orders.ShipState,
Orders.ShipPostalCode,
Orders.ShipCountry,
OrderDetails.ProductCode,
OrderDetails.ProductPrice,
OrderDetails.Quantity
FROM Orders INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID
WHERE (OrderDetails.ProductPrice <> 0) AND (Orders.SalesTax1 <> 0) AND (OrderDetails.Quantity <> 0) AND (Orders.ShipDate NOT LIKE 'Null') AND (month(Orders.ShipDate)=5) AND (year(Orders.ShipDate)=2016)
GROUP BY Orders.OrderID, Orders.ShipCompanyName, Orders.ShipFirstName, Orders.ShipLastName, Orders.Shipaddress1, Orders.ShipAddress2, Orders.ShipCity, Orders.ShipState, Orders.ShipPostalCode, Orders.ShipCountry, OrderDetails.ProductCode, OrderDetails.ProductPrice, OrderDetails.Quantity
UNION
SELECT
CAST(Orders.OrderID AS VARCHAR) + ' Total',
' ' ,
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
cast(sum(OrderDetails.ProductPrice) AS MONEY),
' '
FROM Orders INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID
WHERE (OrderDetails.ProductPrice <> 0) AND (Orders.SalesTax1 <> 0) AND (OrderDetails.Quantity <> 0) AND (Orders.ShipDate NOT LIKE 'Null') AND (month(Orders.ShipDate)=5) AND (year(Orders.ShipDate)=2016)
GROUP BY Orders.OrderID, OrderDetails.ProductPrice
ORDER BY CAST(Orders.OrderID AS VARCHAR
Here is a .jpg of the first few lines of results:
)
As you can see from the results. The Total line is not a single total of all OrderIDs and in some examples it actually adds and totals, but in others it just carries the line down to the total line.
Thank you in advance for any help.