什么是SQL执行此操作?

时间:2018-09-25 02:01:04

标签: sql sql-server tsql

如果我有一个包含两列的表,则分别为客户ID和登录日期/时间。实际上,他们每次登录时,其客户ID和登录日期/时间都会插入此表中。

什么是最有效的SQL,它不仅可以给我列出客户ID,还可以列出过去30天,60天和90天他们登录多少次?

2 个答案:

答案 0 :(得分:5)

您可以使用条件聚合:

select customerid,
       sum(case when logindatetime >= dateadd(day, -30, getdate()) then 1 else 0 end) as cnt_30,
       sum(case when logindatetime >= dateadd(day, -60, getdate()) then 1 else 0 end) as cnt_60,
       sum(case when logindatetime >= dateadd(day, -90, getdate()) then 1 else 0 end) as cnt_90
from logins
where logindatetime >= dateadd(day, -90, getdate())
group by customerid;

答案 1 :(得分:1)

这在功能上与戈登的答案相同,但是我已经开始输入文字,因此我认为我将完成发布。次要区别包括:

  1. 包含一些示例数据
  2. 使用了IIF函数(仅适用于SQL Server 2012 +; case when <predicate> then <value> end的语法糖)
  3. 将datediff封装到一列中,以便不必为每个表达式重写它

代码:

with src (CustId, LoginDt) as
(
    select 1, getdate() - 89 union all
    select 2, getdate() - 90 union all
    select 2, getdate() - 59 union all
    select 3, getdate() - 61 union all
    select 3, getdate() - 31 union all
    select 3, getdate() - 30 union all
    select 3, getdate() - 29 union all
    select 3, getdate() union all
    select 4, getdate() - 12
), logins as
(
    select CustId, LoginDt, DaysSinceLastLogin = datediff(day, getdate(), LoginDt)
    from src
)
select 
    CustId,
    LastLogin = max(loginDt),
    Last30 = sum(iif(DaysSinceLastLogin >= -30, 1, 0)),
    Last60 = sum(iif(DaysSinceLastLogin >= -30, 1, 0)),
    Last90 = sum(iif(DaysSinceLastLogin >= -90, 1, 0))       
from logins
where LoginDt >= dateadd(day, -90, getdate())
group by CustId