Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

SQL Server - Compter les événements qui se produisent de 15 minutes à 14 jours à partir de l'heure de base

With Metrics As
  (
  Select T1.Client, T1.Type
    , Min(eci_Date) As FirstCallDate
  From Table1 As T1
  Group By T1.Client, T1.Type
  )
Select DateAdd(d, DateDiff(d,0,T1.eci_date), 0) As [Day], Type, Count(*) As TotalCalls
  , (
    Select Count(*)
    From Table1 As T2
      Join Metrics As M2
        On M2.Client = T2.Client
          And M2.Type = T2.Type
    Where T2.eci_Date >= DateAdd(mi,15,M2.FirstCallDate)
      And T2.eci_date <= DateAdd(d,15,M2.FirstCallDate)
      And DateAdd(d, DateDiff(d,0,T1.eci_date), 0) = DateAdd(d, DateDiff(d,0,T2.eci_date), 0)
    ) As Total_Repeats
From Table1 As T1
Group By DateAdd(d, DateDiff(d,0,T1.eci_date), 0), Type
Order By [Day] Asc, Type Desc

SQL Fiddle