如何将2列相乘然后对结果进行求和?

时间:2018-01-16 16:20:12

标签: sql sum

我正在学习SQL,我无法在论坛上的任何地方找到我的问题的解决方案。无论如何,我正在使用www.dofactory.com SQL Sandbox,我已经提出了一个问题:

 select customer.LastName, Product.ProductName, OrderItem.Quantity, Product.UnitPrice, OrderItem.Quantity*Product.UnitPrice AS "Quantity x UnitPrice" 
FROM Customer
    JOIN [Order] ON [Order].CustomerID = Customer.ID
    JOIN OrderItem ON OrderItem.OrderId = [Order].ID
    JOIN Product ON Product.Id = OrderItem.ProductId
    where
    [Order].TotalAmount = (select max([Order].TotalAmount) FROM [Order])

结果:

LastNam ProductName    Quantity   UnitPrice      Quantity x UnitPrice
Kloss   Côte de Blaye       60      263.50             15810.00
Kloss   Chartreuse verte    80       18.00             1440.00

现在我想要整列“Quantity x UnitPrice”。我该怎么办?

2 个答案:

答案 0 :(得分:0)

这是SQL Server(T-SQL)。您可以像这样使用SUM和GROUP BY。我已经在子查询中完成了它,这就是我如何处理这种事情。

select LastName, ProductName, Quantity, UnitPrice, SUM(Summary)
from (
select customer.LastName, Product.ProductName, OrderItem.Quantity, Product.UnitPrice, OrderItem.Quantity*OrderItem.UnitPrice AS Summary, [Order].TotalAmount
FROM Customer
JOIN [Order] ON [Order].CustomerID = Customer.ID
JOIN OrderItem ON OrderItem.OrderId = [Order].ID
JOIN Product ON Product.Id = OrderItem.ProductId
where
[Order].TotalAmount = (select max([Order].TotalAmount) FROM [Order])) x
group by LastName, ProductName, Quantity, UnitPrice

答案 1 :(得分:0)

您使用SUM()。像这样:

SELECT SUM(oi.Quantity * oi.UnitPrice) AS Summary
FROM Customer c JOIN
     [Order] o
     ON o.CustomerID = c.ID JOIN
     OrderItem oi
     ON oi.OrderId = o.ID JOIN
     Product p
     ON p.Id = oi.ProductId
WHERE o.TotalAmount = (select max(o2.TotalAmount) FROM [Order] o2);

请注意表别名的使用。它们使查询更容易编写和阅读。