使用 SQL Server T-SQL 语法,您如何找到特定客户的最后/最大交易月份内的所有记录?
鉴于以下记录:
CUSTOMER_ID | TRANSACTION_DATE
------------------------------
00001 | 04/21/2013
00001 | 05/01/2013
00001 | 05/14/2013
00002 | 06/08/2013
00002 | 07/01/2013
00002 | 07/28/2013
查询的输出应如下所示:
CUSTOMER_ID | TRANSACTION_DATE
------------------------------
00001 | 05/01/2013
00001 | 05/14/2013
00002 | 07/01/2013
00002 | 07/28/2013
我想出的最好的是这个查询(未经测试),它看起来非常低效。
select customer_id, transaction_date
from customer_table outer
where concat(month(transaction_date), year(transaction_date)) = (
select concat(month(max(transaction_date)), year(max(transaction_date)))
from customer_table inner
where outer.customer_id = inner.customer_id
)