在没有右连接的情况下执行此查询的最有效方法

时间:2013-07-22 09:40:52

标签: sql sql-server sql-server-2008 join

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).

在没有完全加入的情况下执行此查询的最佳方法是什么? 最有效的,特别是当桌子真正变大时。

1 个答案:

答案 0 :(得分:0)

如何将数据放在子查询中?

select acct, sum(Rangesales), sum(MonthSales) from 
  (select acct, 
       if(amt is null,0, amt) as Rangesales,  
       if (YEAR(saledate) = YEAR(@endDate) and month(saledate) = MONTH(@endDate), amt, 0) as        MonthSales
  from TestSales
  where saledate between @startDate and @endDate
) raw
group by acct