Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL Server:conta gli eventi che si verificano da 15 minuti a 14 giorni dall'ora di 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