mssql联合查询统计字段的问题
我的表是按日期每天一个完全同字段的,比如:buylog20140901buylog20140902buylog20140903...buylog20140930表的字段为...
我的表是按日期每天一个完全同字段的,比如:
buylog20140901
buylog20140902
buylog20140903
...
buylog20140930
表的字段为:
id uid buytype amount goodsname
-------------------------------------------
1 31987 in 39.27 太阳花
2 31987 in 40.5 香蕉花
我现在要统计uid为31987 2014年9月份 每天购买的次数和金额,我的语句如下:
select count(uid) as num,sum(amount) as amount from buylog20140901 where uid='31987'
UNION ALL
select count(uid) as num,sum(amount) as amount from buylog20140902 where uid='31987'
UNION ALL
select count(uid) as num,sum(amount) as amount from buylog20140903 where uid='31987'
一直到
UNION ALL
select count(uid) as num,sum(amount) as amount from buylog20140930 where uid='31987'
这样生成的结果是达到我目的的30条记录
num amount
2 100
11 980
...
5 320
现在的问题就是,执行的时间非常长,需要15-20秒的时候,服务器配置也不差,不知道有没有什么其他更好的方法 展开
buylog20140901
buylog20140902
buylog20140903
...
buylog20140930
表的字段为:
id uid buytype amount goodsname
-------------------------------------------
1 31987 in 39.27 太阳花
2 31987 in 40.5 香蕉花
我现在要统计uid为31987 2014年9月份 每天购买的次数和金额,我的语句如下:
select count(uid) as num,sum(amount) as amount from buylog20140901 where uid='31987'
UNION ALL
select count(uid) as num,sum(amount) as amount from buylog20140902 where uid='31987'
UNION ALL
select count(uid) as num,sum(amount) as amount from buylog20140903 where uid='31987'
一直到
UNION ALL
select count(uid) as num,sum(amount) as amount from buylog20140930 where uid='31987'
这样生成的结果是达到我目的的30条记录
num amount
2 100
11 980
...
5 320
现在的问题就是,执行的时间非常长,需要15-20秒的时候,服务器配置也不差,不知道有没有什么其他更好的方法 展开
3个回答
展开全部
--1建张临时表
if object_id('Tempdb..#tab') >0
drop table #tab
select uid,amount into #tab from buylog20140901 where 1=2
alter table #tab add buydate int
--2用循环将各分表的内容插入到建好的临时表中
declare @sql varchar(8000)
declare @i int
set @i=1
while @i<=30
begin
select @sql='
insert into #tab(buydate,uid,amount)
select '+convert(varchar(2),@i)+' ,uid,amount from buylog201409'+right('00'+convert(varchar(2),@i),2)+' where uid=''31987'' '
exec (@sql)
set @i=@i+1
end
go
--3根据要求读出结果
select count(uid) as num,sum(amount) as amount from #tab where uid='31987' group by buydate order by buydate
if object_id('Tempdb..#tab') >0
drop table #tab
select uid,amount into #tab from buylog20140901 where 1=2
alter table #tab add buydate int
--2用循环将各分表的内容插入到建好的临时表中
declare @sql varchar(8000)
declare @i int
set @i=1
while @i<=30
begin
select @sql='
insert into #tab(buydate,uid,amount)
select '+convert(varchar(2),@i)+' ,uid,amount from buylog201409'+right('00'+convert(varchar(2),@i),2)+' where uid=''31987'' '
exec (@sql)
set @i=@i+1
end
go
--3根据要求读出结果
select count(uid) as num,sum(amount) as amount from #tab where uid='31987' group by buydate order by buydate
更多追问追答
追问
你好,感谢您的回复!不过我的帐号只有查询权限,不能通过您这种方式吧?
追答
有查询权限就可以,拷去执行就好。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询