27,579
社区成员
发帖
与我相关
我的任务
分享
if object_id(N'tempdb..#t') is not null
drop table #t
Go
Create table #t
(type varchar(5),
total int,
day Date)
Insert into #t
select '1',300,'2018-5-4' union all
select '2',1200,'2018-5-5' union all
select '1',200,'2018-5-6' union all
select '1',1200,'2018-5-8' union all
select '2',200,'2018-5-8' union all
select '3',1200,'2018-5-9'
Go
select last_7,type,isnull(SUM(total),0) as subtotal
from
(select convert(varchar(10),dateadd(day,-1*number,GETDATE()),23) as last_7
from master.dbo.spt_values
where type='p' and number<7) as A
left join #t B on A.last_7=B.day
group by last_7,type
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([type] int,[total] int,[day] Date)
Insert #T
select 1,300,'2018-5-4' union all
select 2,1200,'2018-5-5' union all
select 1,200,'2018-5-6' union all
select 1,1200,'2018-5-8' union all
select 2,200,'2018-5-8' union all
select 3,1200,'2018-5-9'
Go
--测试数据结束
SELECT tab.type,
ISNULL(total, 0) total,
tab.[day]
FROM
(
SELECT DATEADD(DAY, number, CONVERT(DATETIME, '2018-05-04')) [day],
t.type
FROM master..spt_values,
(SELECT DISTINCT type FROM #T) t
WHERE master..spt_values.type = 'P'
AND number
BETWEEN 0 AND DATEDIFF(DAY, '2018-05-04', '2018-05-10')
) tab
LEFT JOIN #T
ON tab.[day] = #T.[day] AND #T.type = tab.type