SQL 购买过一种以上通行证的Server 2016用户

SQL Server 2016 users who have purchased more than one type of pass

我试图找出购买了不止一种通行证的用户。不是他们购买了多少通行证。

我的查询是:

select 
    MemberNameFormatted, 
    passtype
from
    Memberships_View_With_Inactive As members
inner join 
    PassType AS PassType on PassType.serviceguid = members.ServiceGUID
where 
    PassType in ('Fee Assistance Pass', 'All Access','Plus Pass','Value Pass')
group by 
    MemberNameFormatted, PassType
having 
    count(all(PassType)) >= 1

这个 returns 并显示了所有用户和他们持有的通行证类型:

我需要的是:只持有两种或两种以上不同通证类型的用户:

一个人每个月都可以更新他们的会员资格,所以我对他们有多少会员资格不感兴趣,只要他们在任何时候持有不同的会员资格即可。大多数人坚持使用一种类型的通行证,因此会员中有数千个条目 table。

如果您只想要成员(如您的问题所述),则可以使用 group by

select m.MemberNameFormatted, pt.passtype
from Memberships_View_With_Inactive m join
     PassType pt
     on pt.serviceguid = m.ServiceGUID
where pt.PassType in ('Fee Assistance Pass', 'All Access', 'Plus Pass', 'Value Pass')
group by m.MemberNameFormatted
having count(distinct pt.passtype) >= 2

如果你也想要通行证,那么:

with mp as (
      select m.MemberNameFormatted, pt.passtype
      from Memberships_View_With_Inactive m join
           PassType pt
           on pt.serviceguid = m.ServiceGUID
      where pt.PassType in ('Fee Assistance Pass', 'All Access', 'Plus Pass', 'Value Pass')
     )
select distinct mp.*
from mp
where exists (select 1
              from mp mp2
              where mp2.MemberNameFormatted= mp.MemberNameFormatted and mp2.passtype <> mp.passtype
             );

您可以使用不同的

进行自连接
select distinct
   t1.MemberNameFormatted, 
   t1.passtype
from
   Table as t1
join
   Table as t2 on
   t2.MemberNameFormatted = t1.MemberNameFormatted and
   t2.passtype <> t1.passtype
order by
   t1.MemberNameFormatted, 
   t1.passtype