Datediff SQL-server查询统计数据,包括count&通过...分组

时间:2014-05-23 09:08:09

标签: sql-server join datediff

所以我想要达到的目的是计算有多少用户触发EventCode 90相对于他们上次收到通知的时间。

源表如下:

ServiceOne

UserNr         RegisteredUntil            NotificationMonth
532091985      2016-05-15 00:00:00.000    5
950628185      2016-03-15 00:00:00.000    3
561007126      2016-09-15 00:00:00.000    9

通知

UserNr         NotificationNr     NotificationDate            Service
532091985      134567             2013-04-16 00:00:00.000     1
532091985      153468             2014-04-15 00:00:00.000     1
950628185      235481             2014-02-17 00:00:00.000     1
561007126      354812             2012-08-15 00:00:00.000     1

事件日志

Time                        EventCode      UserNr
2012-12-19 00:00:00.000     90             561007126
2014-05-02 00:00:00.000     90             120456873
2009-08-24 00:00:00.000     90             935187423

我想要的表是这样的:

CancMonth CancAmount
0         49091
1         53564
2         14308

到目前为止我所拥有的是

Select Max(datediff(month, I.NotificationDate, E.Time)  ) as CancMonth
,Count(datediff(month, I.NotificationDate, E.Time)  ) as CancAmount

From ServiceOne P, Eventlog E, Notifications N
Where P.UserNr=E.UserNr
AND P.UserNr=N.UserNr
AND E.EventCode = 90 --EventCode 90 is both flagging for deregistration and manual deregistration
AND N.Service=1
AND P.Status In (0,4) -- 0 is not registered and 4 is flagged for deregistration
AND datediff(month, N.NotificationDate, E.Time ) < 13 --Notifications are sent once a year
AND N.NotificationDate < E.Time

Group By datediff(month, N.NotificationDate, E.Time )
Order By CancMonth

我计算了这个记录的总记录数量,并且它比ServiceOne中的被动和标记用户多得多35,000个。

非常感谢帮助,因为这让我在过去几天感到头疼。

编辑:我添加了我的源表和所有可能可用的列以及一些随机样本数据

1 个答案:

答案 0 :(得分:0)

这是你在寻找什么?

--I assue that Latest NotificationDate has Largest NotificationNr

SELECT      MAX(DATEDIFF(MONTH, I.NotificationDate, E.Time)) AS CancMonth,
            COUNT(DATEDIFF(MONTH, I.NotificationDate, E.Time)) AS CancAmount
FROM        ServiceOne P 
JOIN        Eventlog E ON P.UserNr  =E.UserNr 
JOIN        (
            SELECT  N.*
            FROM    Notifications N
            JOIN    (
            SELECT  UserNr,
                    MAX(NotificationDate) NotificationDate,
                    MAX(NotificationNr) NotificationNr        
            FROM    Notifications) LU 
    ON      N.UserNr = LU.UserNr 
    AND     N.NotificationDate = LU.NotificationDate 
    AND     N.NotificationNr = LU.NotificationNr
            ) N ON P.UserNr = N.UserNr 
WHERE       E.EventCode = 90 
AND         N.Service=1
AND         P.Status In (0,4)
AND         DATEDIFF(MONTH, N.NotificationDate, E.Time ) < 13
AND         N.NotificationDate < E.Time
GROUP BY    DATEDIFF(MONTH, N.NotificationDate, E.Time )
ORDER BY    CancMonth