MS SQL如何选择最后N条记录相同的客户端

时间:2015-03-31 12:27:03

标签: sql tsql

我有一个由ClientID,ActionDate,Action和Result组成的表。

我需要选择在给定日期范围内仅具有特定操作/结果组合的不同客户端。

举例说明:

  1. 我需要不同的clientID,其最后5个Action / Result是Call / NoAnswer。
  2. 我需要在过去30天内只有Call / NoAnswer的不同clientID。
  3. 由于

1 个答案:

答案 0 :(得分:2)

1

select ClientID from
(
select 
  ClientID,
  Action,
  Result,
  row_number() over (partition by ClientID order by ActionDate desc) as num
from ClientActions
) T -- the latest 5 action/result
where rnum <= 5
group by ClientID
having MAX(case when Action='Call' and Result = 'NoAnswer' then 0 else 1 end) = 0

2

select ClientID
from ClientActions
where DATEDIFF(DAY, ActionDate, GETDATE()) <= 30
group by ClientID
having MAX(case when Action='Call' and Result = 'NoAnswer' then 0 else 1 end) = 0