我有一个表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
...有什么想法吗?
发布于 2018-08-02 19:10:10
下面的查询将计算每一次访问/奖励/购买对于给定名称的发生频率,如果相应的结果为1/1/0,则将返回表中所有带有该名称的记录。
如果需要微调(例如,其中任何一项的计数>1等)这可以通过摆弄“拥有”子句中的数字来实现。添加要检查的其他类别也是如此。
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也可以使用,但有点不同。
https://stackoverflow.com/questions/51660267
复制相似问题