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 に答える