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

在没有直接连接的情况下执行此查询的最佳方法是什么?最有效的,尤其是当桌子变大的时候。

4

1 回答 1

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
于 2013-07-22T10:03:50.223 回答