在SQL查询中应用if逻辑?

在SQL查询中应用if逻辑?,sql,if-statement,rjdbc,Sql,If Statement,Rjdbc,我的数据库表的格式如下所示: 本年度=2017年 ID Bought Year 1 A 2016 1 A 2015 2 A 2013 2 B 2015 2 B 2014 3 A 2014 4 A 2014 4 A 2015 4 A 2016

我的数据库表的格式如下所示:

本年度=2017年

ID     Bought    Year
1       A        2016
1       A        2015
2       A        2013
2       B        2015 
2       B        2014
3       A        2014
4       A        2014 
4       A        2015  
4       A        2016 
列出过去两年购买产品“A”的客户(在T-1和T-2年购买)

Ans-ID:1和4

如何在R中使用

lasttwoyearcustlist=DBgetQuery(conn, "Query") 

一种方法是根据一年中的数字计算

select id 
from my_table 
where  bought = 'A'
and year in ( 2016, 2015) 
group by id
having count(distinct year) =2

一种方法是根据一年中的数字计算

select id 
from my_table 
where  bought = 'A'
and year in ( 2016, 2015) 
group by id
having count(distinct year) =2