sqlserver 将union查询写入新表

-- 写入临时表
select * into #temp

-- 写入新表
use Report
go
if exists(select name from sys.objects where name='消费_月')
	drop table 消费_月
go
use [Account Management]
go
select t.* into Report.dbo.消费_月 from 
(
	(select 月度='201901', 用户名, 类别, sum(金额) sum_of_month from 消费 where 日期 between '20190101' and '20190131'
	group by 用户名, 类别)
	union all
	(select 月度='201902', 用户名, 类别, sum(金额) sum_of_month from 消费 where 日期 between '20190201' and '20190228'
	group by 用户名, 类别)
	union all
	(select 月度='201903', 用户名, 类别, sum(金额) sum_of_month from 消费 where 日期 between '20190301' and '20190331'
	group by 用户名, 类别)
	union all
	(select 月度='201904', 用户名, 类别, sum(金额) sum_of_month from 消费 where 日期 between '20190401' and '20190430'
	group by 用户名, 类别)
	union all
	(select 月度='201905', 用户名, 类别, sum(金额) sum_of_month from 消费 where 日期 between '20190501' and '20190531'
	group by 用户名, 类别)
	union all
	(select 月度='201906', 用户名, 类别, sum(金额) sum_of_month from 消费 where 日期 between '20190601' and '20190630'
	group by 用户名, 类别)
) t

你可能感兴趣的:(SQL)