我有一个包含以下交易数据的表A:
ID Name Type
1 Albert Rewards
2 Albert Visit
3 Ruddy Rewards
4 Ruddy Visit
5 Ruddy Purchase
6 Mario Rewards
7 Mario Visit
...
我想要一个表,该表仅选择具有使用“奖励”和“访问”类型但未购买的人的名字的行,如下所示:
ID Name Type
1 Albert Rewards
2 Albert Visit
6 Mario Rewards
7 Mario Visit
...
有什么想法吗?
答案 0 :(得分:1)
下面的查询将为每个访问/奖励/购买次数计算给定名称的发生频率-如果相应结果为1/1/0,则将返回该名称的表中的所有记录。
如果需要微调(例如其中任何一个的计数> 1等的情况),可以通过摆弄“ having”子句中的数字来完成。添加其他类别以进行检查也是如此。
select *
from mytable a
where exists (select b.name,
sum(case when b.type='Rewards' then 1 else 0 end),
sum(case when b.type='Visit' then 1 else 0 end),
sum(case when b.type='Purchase' then 1 else 0 end)
from mytable b
where b.name=a.name
group by b.name
having sum(case when b.type='Rewards' then 1 else 0 end) = 1
and
sum(case when b.type='Visit' then 1 else 0 end) = 1
and
sum(case when b.type='Purchase' then 1 else 0 end) = 0);
为完成起见:SQLFiddle with 2 queries First query also works, but a little differently