我尝试编写报告并尝试了多种方法,我的问题是数据需要分组的方式确实使查询复杂化。请参阅我附上的查询,这是我得到的最接近的查询。我写了另一个我认为可行的查询,但在执行了20分钟之后我就把它杀死了。这是查询:
SELECT right(EV.Name, (Len(EV.Name) - ABS(Charindex('-',EV.Name )))) AS [Store Name],
sum(OLI.Quantity) as [Total Packages], sum(OPUI.TaxAmount) as [Total Tax],
sum(OPUI.ShippingAmount) as [Total Shipping], sum(OPUI.OrderTotal) as [Order Total],
sum(PP.Cost) as [Total Cost],
sum(case when OLI.PackageID = 11 then 1 else 0 end) AS [Package 1],
sum(case when OLI.PackageID = 12 then 1 else 0 end) AS [Package 2],
sum(case when OLI.PackageID = 13 then 1 else 0 end) AS [Gift Package],
sum(case when OLI.PackageID = 15 then 1 else 0 end) AS [Digital Download],
sum(case when OLI.PackageID = 16 then 1 else 0 end) AS [Magnets],
sum(case when OLI.PackageID = 17 then 1 else 0 end) AS [Mugs],
sum(case when OLI.PackageID = 20 then 1 else 0 end) AS [Puzzles],
sum(case when OLI.PackageID = 18 then 1 else 0 end) AS [3.5x5 Cards],
sum(case when OLI.PackageID = 19 then 1 else 0 end) AS [5x7 Cards],
sum(case when OLI.PackageID = 14 then 1 else 0 end) AS [4x8 Cards],
sum(case when OLI.PackageID = 50 then 1 else 0 end) AS [Postcards]
FROM OrderPUInfo OPUI
INNER JOIN Orders ORD ON ORD.OrderID = OPUI.OrderID
INNER JOIN OrderPULineItems OLI ON OLI.OrderID = ORD.OrderID
INNER JOIN PUConsumerData CD ON CD.ConsumerDataID = OPUI.ConsumerDataID
INNER JOIN PUEvents EV ON EV.EventID = CD.EventID
INNER JOIN PUPackages PP ON PP.PackageID = OLI.PackageID
WHERE CONVERT(date,ORD.OrderDate) <= '2013-12-24' AND CONVERT(date,ORD.OrderDate) > '2013-11-08' AND
EV.EventID > 3914 and EV.EventId < 3977 and EV.TourID = 283
GROUP BY EV.Name
ORDER BY EV.Name
我确信您可以看到问题...当给定订单的订单总数超过OrderPULineItem时,订单总数会被夸大。我的想法是对不同的包进行外部应用,但是从未返回结果,查询只是旋转直到超时。然后我尝试为总计做一个子查询,但同样,因为子查询几乎是没有行项目的整个查询,它执行的时间也很长。
这里的大师们已经通过简单的优化帮助了我最初写的歌,所以我希望你们都能再次帮助。