从表面上看,这似乎是一个简单的where子句,但鉴于下面的数据,我只希望我的查询返回帐户B的销售交易,条件是只显示那些没有任何帐户的帐户销售日期超过2015年。
Acct Sale Date
A 2030
A 2018
A 2015
B 2015
B 2014
B 2013
C 2020
C 2015
C 2012
答案 0 :(得分:1)
做GROUP BY
。使用HAVING
仅返回上一期SaleDate< = 2015:
select acct
from tablename
group by acct
having max(SaleDate) <= 2015
如果您想要这些帐户的所有列和所有行:
select t.*
from tablename t
join (select acct, max(SaleDate) as maxSaleDate
from tablename
group by acct) t2
on t.acct = t2.acct
where t2.maxSaleDate <= 2015
答案 1 :(得分:1)
如果您需要结果中的每笔交易,可以使用NOT EXISTS
:
SELECT *
FROM YourTable as T
WHERE NOT EXISTS(SELECT 1 FROM YourTable
WHERE SaleDate >= 2015
AND Acct = T.Acct);