以下查询返回以下输出。
输出
BrandName Amount
brand1 314.00
brand1 24.00
brand2 75.00
brand2 48.00
所需的输出是获得每个品牌的总金额,如下所示
BrandName Amount
brand1 338.00
brand2 123.00
查询
SELECT Brands.BrandName,
SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge - ((SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge) * Orders.Discount / 100) AS Amount
FROM dbo.Orders
INNER JOIN dbo.Outlets
ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.OrderDetails
ON dbo.OrderDetails.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Brands
ON dbo.Brands.BrandID = dbo.Outlets.BrandID
GROUP BY
Orders.OrderID,
dbo.Orders.DeliveryCharge,
Orders.Discount,
Brands.BrandName
答案 0 :(得分:1)
您可以使用Common Table Expression
作为您的场景
With MyGroupCte as
(
SELECT Brands.BrandName,
SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge - ((SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge) * Orders.Discount / 100) AS Amount
FROM dbo.Orders
INNER JOIN dbo.Outlets
ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.OrderDetails
ON dbo.OrderDetails.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Brands
ON dbo.Brands.BrandID = dbo.Outlets.BrandID
GROUP BY
Orders.OrderID,
dbo.Orders.DeliveryCharge,
Orders.Discount,
Brands.BrandName
)
SELECT BrandName, SUM(Amount) FROM MyGroupCte
GROUP BY BrandName;
答案 1 :(得分:0)
这样做:
SELECT grp.BrandName,sum(Amount)as Total_Amount from
(SELECT Brands.BrandName,
SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge - ((SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge) * Orders.Discount / 100) AS Amount
FROM dbo.Orders
INNER JOIN dbo.Outlets
ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.OrderDetails
ON dbo.OrderDetails.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Brands
ON dbo.Brands.BrandID = dbo.Outlets.BrandID
GROUP BY
Orders.OrderID,
dbo.Orders.DeliveryCharge,
Orders.Discount,
Brands.BrandName) as grp
group by BrandName