Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT multiple with sum

Tags:

sql

select

sum

I'm trying to do a select SUM while doing other selects at the same. My current script:

SELECT Orders.OrderID,SUM(Trackingnumbers.Shipment_Cost) AS Shipping_Cost
FROM Orders 
INNER JOIN Trackingnumbers
ON Orders.OrderID = TrackingNumbers.OrderID
WHERE Orders.OrderStatus = 'Shipped' AND Orders.ShipDate > (GETDATE()-6) AND Orders.PaymentAmount = Orders.Total_Payment_Received
Group By Orders.OrderID

I want to SELECT more columns, but I cannot because I am using the SUM function so it doesn't work, how can I separate the sum functions from the rest of the attributes so the CSV file has all of the columns plus the SUM of Trackingnumber.Shipment_Cost in one column?

like image 592
henryaaron Avatar asked Sep 04 '25 17:09

henryaaron


1 Answers

You can use a subquery.

SELECT *
    ,(
        SELECT SUM(Shipment_Cost)
        FROM Trackingnumbers
        WHERE Trackingnumbers.OrderID = Orders.OrderID
    ) AS Shipping_Cost
FROM Orders
WHERE Orders.OrderStatus = 'Shipped'
    AND Orders.ShipDate > (GETDATE()-6)
    AND Orders.PaymentAmount = Orders.Total_Payment_Received
like image 97
Peter Majeed Avatar answered Sep 06 '25 16:09

Peter Majeed