我有以下查询(在我的系统中)获得拥有超过6个会员资格的会员总数....
select count(*) as MemberCount from (
SELECT count(membership.memberid) as MembershipCount from Membership, Package
WHERE membership.PackageId = Package.Id
AND membership.DiscountPercentage != 100
AND Package.PackageTypeId != 1
AND membership.MembershipStateId != 5
AND Membership.LocationId = 1
group by memberid
having count(membership.memberid) > 6
) NonTrialMemberships
我需要做的是留下外部加入“拥有”部分的临时表,这样我就可以获得超过1,2,3,4,5,6的成员数量列表, 7,8,9,10会员资格
having count(membership.memberid) > 6 <------(OUTER JOIN THIS)
我创建了一个临时表用作连接但不确定如何使用它。我还看到使用内存表可能比临时表更有效...
create table #Temp
(
Num int,
)
DECLARE @i int = 0
DECLARE @total int = 10
WHILE @i < @total
BEGIN
SET @i = @i + 1
Insert Into #Temp values (@i)
END
select * from #Temp
select count(*) as MemberCount from (
SELECT count(membership.memberid) as MembershipCount from Membership, Package
WHERE membership.PackageId = Package.Id
AND membership.DiscountPercentage != 100
AND Package.PackageTypeId != 1
AND membership.MembershipStateId != 5
AND Membership.LocationId = 1
group by memberid
having count(membership.memberid) > 6
) NonTrialMemberships
If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
Drop Table #Temp
End
任何指导都将不胜感激。
谢谢。
答案 0 :(得分:1)
尝试使用#temp。
select #temp.num, count(*)
from #temp
left join
(
SELECT count(membership.memberid) as MembershipCount from Membership, Package
WHERE membership.PackageId = Package.Id
AND membership.DiscountPercentage != 100
AND Package.PackageTypeId != 1
AND membership.MembershipStateId != 5
AND Membership.LocationId = 1
group by memberid
having count(membership.memberid) > 1
) ntm
on ntm.MembershipCount > #temp.num
group by #temp.num
绝对会根据要求计算每个&gt; 1,&gt; 2,...,&gt; 10组中有11个会员资格的用户。
答案 1 :(得分:0)
我会采用不同的方式
lavoro2
答案 2 :(得分:0)
您想要选择计数,并获得每个计数(听起来很奇怪,但实际上非常简单):
SELECT MemberCount, Count(*)
FROM
(
SELECT count(membership.memberid) as MemberCount
FROM Membership, Package
WHERE membership.PackageId = Package.Id
AND membership.DiscountPercentage != 100
AND Package.PackageTypeId != 1
AND membership.MembershipStateId != 5
AND Membership.LocationId = 1
group by memberid
having count(membership.memberid) > 6
) t
group by MemberCount
order by MemberCount
您提到您希望获得拥有1,2,3等会员资格的会员数量。如果是这种情况,您将需要从查询中删除以下行:
having count(membership.memberid) > 6
这样做将包括所有计数的计数(再次,听起来很奇怪),这似乎是您的要求。如果您想澄清或者我误解了您的问题,请发表评论。