代码:
if Object_id('Tempdb..#tmp') IS NOT NULL DROP TABLE #tmp; declare @pageCount int,@pageIndex int select @pageCount = 20,@pageIndex = 1; with cte as( select * from ( select ROW_NUMBER() OVER(Order by a.UserID ) as row--分页 ,count(b.UserID) over(PARTITION BY b.UserID) as xsCarCount--车辆数量 ,count(b.UserID) over(PARTITION BY b.UserID ) as yqUserCount--客户数量 ,ROW_NUMBER() OVER(PARTITION BY a.UserID ORDER BY a.UserID) as rownum--过滤重复 ,a.[UserID] ,a.[UserName] ,a.[UserType] ,a.[HoldID] ,a.[StartTime] ,a.[EndTime] ,a.[Email] ,a.[MobilePhone] from std_UserInfo a with (nolock) left join std_UserInfo c on a.MobilePhone=c.InviteCode left hash join std_UserObj b on c.UserID=b.UserID where a.U_UserType=1 and a.holdID=10 and a.isDeleted=0 and a.StartTime BETWEEN '2015-06-11 00:00:00' and '2015-06-11 15:01:32' )temp where temp.rownum=1 ) select * into #tmp from cte; select * from #tmp where row between (@pageIndex-1)*@pageCount+1 and @pageCount*@pageIndex ; select count(1) as countNumber from #tmp
博客园代码格式问题导致不好看 星哥你提出到sql里面看吧
结果
yq的userCount有问题
原因
SELECT[UserID], [UserName],[MobilePhone],InviteCode FROM std_UserInfo WHERE USERNAME ='11112222' SELECT [UserID],[UserName],[MobilePhone],InviteCode FROM std_UserInfo WHERE USERNAME ='22223333' SELECT * FROM STD_USEROBJ WHERE USERID=845 --用户为11112222的 他邀请的用户为22223333 (用户11112222的MobilePhone等于用户为 22223333的InviteCode) --总结 11112222下面有1个用户 同理 要是其他的用户的InviteCode也等于11112222 MobilePhone 则有2 个 --STD_USEROBJ 下面的2223333的userid 为 845说明有3个车 这个统计没有问题
如图:
木有测试数据,也太难得猜了点吧。明白你的意思了,不过你这sql语句,没数据不太好改的。
个人觉得你的客户数量在count的时候应该用c.UserId,而不是用b的。
就是这一句有问题 ,count(b.UserID) over(PARTITION BY b.UserID ) as yqUserCount--客户数量
@s_p: 直接用子查询也是非常简单的查询方式。
@幻天芒: 这样
select count(a.UserID), a.[UserName] from std_UserInfo c,std_UserInfo a where a.MobilePhone=c.InviteCode and a.MobilePhone!='' and c.InviteCode!=''
group by a.UserID ,a.[UserName]
不能用类似上面的那个查询解决ma ?
@s_p: 你没看我的第一个回答的补充?你的xsCarCount和yqUserCount实现成一样的了。是可以按照你的写法实现的,只是不直观。