CREATE TABLE [dbo].[TestSales](
[id] [int] IDENTITY(1,1) NOT NULL,
[saledate] date NULL,
[acct] varchar(20) NULL,
[Amt] [decimal](18,2) NULL
)
GO
insert into TestSales values('2013-07-20','Acct1',1000)
insert into TestSales values('2013-07-20','Acct1',2000)
insert into TestSales values('2013-07-20','Acct1',500)
insert into TestSales values('2013-08-2','Acct2',400)
insert into TestSales values('2013-08-2','Acct2',1000)
insert into TestSales values('2013-08-2','Acct2',1000)
select * from TestSales
declare @startDate date = '2013-07-20',@endDate date = '2013-08-2'
select t1.acct,isnull(Rangesales,0) Rangesales,isnull(Monthsales,0)Monthsales
from (select acct,isnull(SUM(amt),0) as Rangesales from TestSales
where saledate between @startDate and @endDate
group by acct) as t1
left outer join
(select acct,isnull(SUM(amt),0) as Monthsales from TestSales
where YEAR(saledate) = YEAR(@endDate) and month(saledate) = MONTH(@endDate)
group by acct) as t2 on
t1.acct = t2.acct
需要得到总数monthly sales for(@endDate) and total sales between(@startDate and @endDate).
在没有直接连接的情况下执行此查询的最佳方法是什么?最有效的,尤其是当桌子变大的时候。