我最初只是写了一个查询来找出每个客户的年度总订单数大于 1。在 1.query 中,我过滤了结果集并将其与另一个找到客户名称的结果集连接起来。奇怪的是,我猜首先过滤器会产生更好的性能,因为需要加入的结果更少。所以我写了第二个查询先加入然后过滤,这看起来比第一个查询更整洁。结果与我预期的相同,因为结果中的所有时间都较低。但我不确定哪个时间最重要?还是这个案子只是巧合?如何考虑性能?
use [AdventureWorks2012]
set statistics time on;
--1.filter first,join second
select tempC.*,tempP.FirstName,tempP.LastName
from
(select Year(OrderDate) As OrderYear,CustomerID,count(CustomerID) As CustomerOrderAmt
from Sales.SalesOrderHeader
group by Year(OrderDate),CustomerID
having count(CustomerID) >1
) as tempC
join(
select p.FirstName,p.LastName,c.CustomerID
from Person.Person as p join Sales.Customer as c on c.PersonID=p.BusinessEntityID
) as tempP
on tempC.CustomerID=tempP.CustomerID
order by tempC.OrderYear,tempC.CustomerID
GO
--2.join first,filter second
select Year(so.OrderDate) As Orderdate,so.CustomerID,count(so.CustomerID) As CustomerOrderAmt,p.FirstName,p.LastName
from Sales.SalesOrderHeader as so
join Sales.Customer as C on so.CustomerID=c.CustomerID
join Person.Person as p on c.PersonID=p.BusinessEntityID
group by Year(so.OrderDate),so.CustomerID,p.FirstName,p.LastName
having count(so.CustomerID)>1
go