|
发表于 2011-10-31 12:18:13
|
显示全部楼层
Re:/统計表问
SQL code --> --> (Roy)生成測試數據
if not object_id('Tempdb..#Customer') is null
drop table #Customer
Go
Create table #Customer([code] nvarchar(4),[pay_date] nvarchar(2))
Insert #Customer
select N'0001',N'01' union all
select N'0002',N'25' union all
select N'0003',N'31'
Go
--> --> (Roy)生成測試數據
if not object_id('Tempdb..#invoice') is null
drop table #invoice
Go
Create table #invoice([code] nvarchar(4),[total] int,[invoice_date] Datetime)
Insert #invoice
select N'0001',10000,'2011-07-11' union all
select N'0001',10000,'2011-08-21' union all
select N'0001',10000,'2011-09-01' union all
select N'0001',11000,'2011-09-10' union all
select N'0003',12000,'2011-09-02'
Go
declare @dt nvarchar(7)
set @dt='2011-09'
Select a.[code],b.[total] as [total]
,case when day(cast(@dt+'-01' as datetime)-1)<=[pay_date] then cast(@dt+'-01' as datetime)-1
else dateadd(m,-1,@dt+'-'+[pay_date]) end as dt1
,case when day(dateadd(m,1,cast(@dt+'-01' as datetime))-1)<=[pay_date] then dateadd(m,1,cast(@dt+'-01' as datetime))-1
else @dt+'-'+[pay_date] end as dt2
from #Customer as a
left join
(select [code],sum([total]) as [total] from #invoice where convert(varchar(7),[invoice_date],120)=@dt group by [code] ) as b
on a.[code]=b.[code]
/*
code total dt1 dt2
0001 21000 2011-08-01 00:00:00.000 2011-09-01 00:00:00.000
0002 NULL 2011-08-25 00:00:00.000 2011-09-25 00:00:00.000
0003 12000 2011-08-31 00:00:00.000 2011-09-30 00:00:00.000
*/ |
|