日期:2014-05-16  浏览次数:20635 次

求写一条sql语句。。。统计用的。。。
Alter PROCEDURE [dbo].[statisticsMoneyInfo]
@DTime datetime, --时间
@DTimeEnd datetime, --时间
@PSTypeID int,
@iPageSize int --页面大小
,@iIndexPage int --多少页
,@xiadan money output --下单
,@cedan money output --撤单
,@jiangli1 money output --奖励
,@jiangli2 money output --奖励2
AS
BEGIN

Select UserID
,row_number() over (order by userId asc) as rowNum --行号,ID排序
into #temp100 --存入临时表
from UserInfo where AId=0 

select UserID as userid into #userIdTable from #temp100 where rowNum between @iPageSize*(@iIndexPage-1)+1 and (@iPageSize*@iIndexPage)--查询要统计的顶级代理UserId
--#userIdTable所有的要统计的UserId 都在这个里面。下面是对每个userid统计,不知道不用循环怎么统计,
DECLARE @AgentId int; --
set @AgentId=0
SELECT @AgentId = count(*) FROM #userIdTable
while @AgentId>0
begin
select
@AgentId as 用户ID,
sum(case ChangeMoneyInfo.ChangeTypeID when 1 then changeMoney else 0 end) as 下单,
sum(case ChangeMoneyInfo.ChangeTypeID when 3 then changeMoney else 0 end) as 撤单,
sum(case ChangeMoneyInfo.ChangeTypeID when 2 then changeMoney else 0 end) as 奖励,
sum(case ChangeMoneyInfo.ChangeTypeID when 4 then changeMoney else 0 end) as 奖励2
into #temp --存入临时表
from dbo.ChangeMoneyInfo
where 1=1
and PSTypeID=isnull(@PSTypeID,PSTypeID)
and (ChangeMoneyInfo.userId in ((select UserID from Userinfo where AllAgentId like '%|'+cast(@AgentId as varchar(10))+'|%' or UserID=@AgentId)))--团队会员) 
and ChangeTime>=Isnull(@DTime,ChangeTime)
and ChangeTime<=Isnull(@DTimeEnd,ChangeTime)

delete from #userIdTable where userid=@AgentId
end
drop table #userIdTable drop table #temp
END


消息 2714,级别 16,状态 6,过程 statisticsMoneyInfo,第 27 行
数据库中已存在名为 '#temp' 的对象。



报了一个这样的错误,还有我不想用循环。。。怎么统计。。。#userIdTable 这个临时表就包含了所有要统计的userId
------解决方案--------------------
Alter PROCEDURE [dbo].[statisticsMoneyInfo]
@DTime datetime, --时间
@DTimeEnd datetime, --时间
@PSTypeID int,
@iPageSize int --页面大小
,@iIndexPage int --多少页
,@xiadan money output --下单
,@cedan money output --撤单
,@jiangli1 money output --奖励
,@jiangli2 money output --奖励2
AS
BEGIN
 CREATE TABLE #temp100(USERID INT,rowNum int)
 CREATE TABLE  #temp (用户ID INT,下单 INT,撤单 INT ,奖励 INT,奖励2 INT  )--存入临时表
 INSERT INTO into #temp100
Select UserID
,row_number() over (order by userId asc) as rowNum --行号,ID排序
 --存入临时表
from UserInfo where AId=0 

select UserID as userid into #userIdTable from #temp100 where rowNum between @iPageSize*(@iIndexPa