以下查询获取某个商店的总销售额。
输出:
SourceName Amount
------------------------
Call Center 2997.00
Delivero Credit 5879.00
Eat Easily Cash 57.00
如果我有一个出口列表,例如出口1和出口2,我希望按每个出口的来源获得总销售额,如果没有销售销售额值应为零,那么输出将是。
SourceName outlet 1 outlet 2
-----------------------------------
Call Center 2997.00 500
Delivero Credit 5879.00 0
Eat Easily Cash 57.00 66
以下问题的问题是双倍DeliveryCharge
它应该是SUM((OrderDetails.Quantity * OrderDetails.UnitPrice)) + Orders.DeliveryCharge - ((SUM((OrderDetails.Quantity * OrderDetails.UnitPrice))) * Orders.Discount / 100)
更新了查询:
SELECT
s.SourceName,
SUM(CASE
WHEN o.OutletID ='1' THEN ((ord.Quantity * ord.UnitPrice) + ordd.DeliveryCharge)
ELSE 0
END) AS [Outlet 1],
SUM(CASE
WHEN o.OutletID ='1' THEN ((ord.Quantity * ord.UnitPrice) + ordd.DeliveryCharge)
ELSE 0
END) AS [Outlet 2]
FROM
dbo.Orders ordd
INNER JOIN
dbo.Outlets o ON ordd.OutletID = o.OutletID
INNER JOIN
dbo.OrderDetails ord ON ord.OrderID = ordd.OrderID
LEFT OUTER JOIN
dbo.Sources s ON s.SourceID = ordd.SourceID
WHERE
ordd.OrderID NOT IN (SELECT CanceledOrders.OrderID
FROM CanceledOrders)
AND ordd.OrderDate BETWEEN '2017-05-1 10:00:00.000' AND '2017-06-1 04:00:00.000'
GROUP BY
s.SourceID, s.SourceName
ORDER BY
s.SourceName
答案 0 :(得分:1)
您目前正在使用源名称进行两次分组,这对我来说毫无意义。除此之外,我认为您可以通过从GROUP BY
中删除插座名称来获取所需的输出,而是转向该列。此外,我重构了您的查询,以便为每个订单汇总子查询中的订单详细信息。这应该解决您在交付费用以及可能的其他领域中看到的重复问题。
WITH MyGroupCte AS (
SELECT
s.SourceName,
SUM(CASE WHEN out.OutletName = 'outlet 1'
THEN ((1 - (o.Discount / 100)) * od.OrderPrice) + o.DeliveryCharge
ELSE 0 END) AS [outlet 1],
SUM(CASE WHEN out.OutletName = 'outlet 2'
THEN ((1 - (o.Discount / 100)) * od.OrderPrice) + o.DeliveryCharge
ELSE 0 END) AS [outlet 2]
FROM dbo.Orders AS o
INNER JOIN dbo.Outlets AS out
ON o.OutletID = out.OutletID
INNER JOIN
(
SELECT
OrderID,
SUM(od.Quantity * od.UnitPrice) AS orderPrice
FROM dbo.OrderDetails
GROUP BY OrderId
) od
ON od.OrderID = o.OrderID
INNER JOIN dbo.Sources AS s
ON s.SourceID = o.SourceID
WHERE
out.OutletID = '6' AND
o.OrderID NOT IN (SELECT OrderID FROM CanceledOrders) AND
o.OrderDate
BETWEEN '2017-05-1 10:00:00.000' AND '2017-06-1 04:00:00.000'
GROUP BY
o.OrderID,
s.SourceName
)
SELECT
SourceName,
[outlet 1],
[outlet 2]
FROM MyGroupCte;
请考虑使用别名,这样可以使查询更容易阅读和格式化。