带SELECT的SQL SELECT倍数

时间:2011-12-13 02:28:07

标签: sql select sum

我正在尝试选择SUM同时进行其他选择。我目前的剧本:

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

我想选择更多的列,但我不能,因为我使用的是SUM函数,因此它不起作用,如何将sum函数与其余属性分开,以便CSV文件包含所有列一列中Trackingnumber.Shipment_Cost的和?

4 个答案:

答案 0 :(得分:8)

您可以使用子查询。

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

答案 1 :(得分:3)

这里的想法是您正在使用聚合查询(使用GROUP BY)。这意味着您返回的列通常应该是聚合函数的结果或者您要分组的内容。

根据您使用的平台,有些具有“第一”功能,这可能很有用。

答案 2 :(得分:2)

有几种不同的方法可以实现它。

予。将聚合函数应用于结果中要包含的每一列

SELECT Orders.OrderID, MAX(Orders.ShipDate) As ShipDate, MAX(Orders.OrderStatus) As OrderStatus, 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

II。将所有字段放在GROUP BY子句

SELECT Orders.OrderID, Orders.ShipDate, Orders.OrderStatus, 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

III。使用子查询

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

答案 3 :(得分:0)

您可以根据查询结果进行另一次查询,如下所示:

select b.aaa,b.bbb from (
    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) as a,Orders b where a.OrderID = b.OrderID.