按类型分组汇总统计某一时间段的数据,该如何写?

tatty_bad 2018-05-12 11:12:55
type total day
1 300 2018-5-4
2 1200 2018-5-5
1 200 2018-5-6
1 1200 2018-5-8
2 200 2018-5-8
3 1200 2018-5-9

按照type去分组,然后查询出最近7天的数据,如果当天没有数据,也需要以0显示出来。
如需要查出5月4日-5月10日的
数据格式应该出来为:
type total day
1 300 2018-5-4
1 0 2018-5-5
1 200 2018-5-6
1 0 2018-5-7
1 1200 2018-5-8
1 0 2018-5-9
1 0 2018-5-10
2 0 2018-5-4
2 1200 2018-5-5
2 0 2018-5-6
2 0 2018-5-7
2 200 2018-5-8
2 0 2018-5-9
2 0 2018-5-10
3 0 2018-5-4
3 0 2018-5-5
3 0 2018-5-6
3 0 2018-5-7
3 0 2018-5-8
3 1200 2018-5-9
3 0 2018-5-10


请教该如何写这句?如果不行的话,那就退一步,不分组,直接指定type的值,但是要实现没有数据的一天按照0显示。
...全文
1639 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
RINK_1 2018-05-13
  • 打赏
  • 举报
回复

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

二月十六 2018-05-12
  • 打赏
  • 举报
回复
--测试数据
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



27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧