选择上个月内的所有记录

时间:2013-08-01 13:26:59

标签: sql-server tsql

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

2 个答案:

答案 0 :(得分: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 FIDDLE EXAMPLE

另一种方法:

;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 FIDDLE EXAMPLE

答案 1 :(得分: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

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

我有here小提琴,但罗马的第一个似乎是最好的。