1

使用 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
)
4

2 回答 2

2
;with CTE as (
    select
        customer_id, transaction_date,
        rank() over(
                   partition by customer_id
                   order by year(transaction_date) desc, month(transaction_date) desc
        ) as row_num
    from customer_table
)
select *
from CTE
where row_num = 1

SQL 提琴示例

另一种方法:

;with CTE as (
    select
        customer_id, dateadd(month, datediff(month, 0, max(transaction_date)), 0) as date
    from @customer_table
    group by customer_id
)
select ct.*
from CTE as c
    inner join @customer_table as ct on
        ct.transaction_date >= c.date and ct.customer_id = c.customer_id

SQL 提琴示例

于 2013-08-01T13:29:42.667 回答
1
SELECT T1.*
FROM  Table1 T1
      JOIN
      (
        SELECT CUSTOMER_ID,
               MAX(TRANSACTION_DATE) AS TRANSACTION_DATE
        FROM   Table1
        GROUP BY CUSTOMER_ID
      ) T2
      ON T1.CUSTOMER_ID = T2.CUSTOMER_ID
WHERE MONTH(T1.TRANSACTION_DATE) = MONTH(T2.TRANSACTION_DATE)
      AND YEAR(T1.TRANSACTION_DATE) = YEAR(T2.TRANSACTION_DATE)

我将以上内容留作参考。

我得出以下结论:

WITH MyCTE AS
(
  SELECT  [CUSTOMER_ID],
          MAX(DATEADD(month, DATEDIFF(month, 0, [TRANSACTION_DATE]), 0)) AS StartOfMonth
  FROM    Table1
  GROUP BY [CUSTOMER_ID]
)

SELECT T2.* 
FROM MyCTE M
Join Table1 T2
ON DATEADD(month, DATEDIFF(month, 0, [TRANSACTION_DATE]), 0) = StartOfMonth

这与罗马的非常相似。不同之处在于我有一个相等而不是大于。执行计划似乎更好,这就是我发布它的原因。

这里有所有的小提琴,但仍然罗曼的第一个似乎是最好的。

于 2013-08-01T13:32:05.313 回答