0

(MySql 引擎)我有一个表格,记录了一个名为“Contacts”的俱乐部的工作人员和成员之间的联系。我需要通过比较成员在整个时间段内该联系之前和之后的平均登录次数来了解最近的联系是否对成员的出席产生了积极影响。登录信息存储在登录表中。用户信息存储在用户表中。

对于在此期间至少有一次联系的俱乐部成员,以下 sql 语句为每个俱乐部成员每次登录(每天 1 次)提取单独的行。我坚持的是找到每个成员在 maxcontactdate 前后的登录总数。

所以我希望结果表的列具有按 recid 分组的行,fk_staff_users_recid

“recid”、“maxcontactdate”、“fk_staff_users_recid”、“pre_maxcontactdate_login_count”、“post_maxcontactdate_login_count”

有人可以帮忙吗?

SELECT
  recid,
  maxcontactdate,
  fk_staff_users_recid,
  logtime
FROM
(
  /* Selects user id, with the staff that made the contact, and the max contact date for that member of staff */
  SELECT fk_users_recid,
          fk_staff_users_recid,
          MAX(contactdate) AS maxcontactdate
  FROM
    contacts
  WHERE
    contactdate BETWEEN '2013-07-20' AND '2013-08-20'
  GROUP BY fk_users_recid, fk_staff_users_recid
)contacts,
users

JOIN
(
  /* Selects all login dates between the dates specified */
  SELECT fk_users_recid,
         DATE(logins.logintime) AS logtime
  FROM
    logins
  WHERE
    logintime BETWEEN '2013-07-20' AND '2013-08-20'
  GROUP BY fk_users_recid, logtime
)logins
ON logins.fk_users_recid = users.recid 

/* Only pull the members who had contacts during the period */
WHERE
users.recid = contacts.fk_users_recid 
4

1 回答 1

2

您可以使用条件计数来执行此操作(CASE WHEN .. 在 count 语句中)

SELECT  recid,
        maxcontactdate,
        fk_staff_users_recid,
        COUNT(CASE WHEN logins.logtime < contacts.maxcontactdate THEN 1 END) AS pre_maxcontactdate_login_count,
        COUNT(CASE WHEN logins.logtime >= contacts.maxcontactdate THEN 1 END) AS post_maxcontactdate_login_count,
        COUNT(*) AS Total_Logins
FROM    (   SELECT  fk_users_recid, fk_staff_users_recid, MAX(contactdate) AS maxcontactdate
            FROM    contacts
            WHERE   contactdate BETWEEN '2013-07-20' AND '2013-08-20'
            GROUP BY fk_users_recid, fk_staff_users_recid
        ) contacts
        INNER JOIN Users    
            ON users.recid = contacts.fk_users_recid 
        INNER JOIN
        (   SELECT  fk_users_recid, DATE(logins.logintime) AS logtime
            FROM    logins
            WHERE   logintime BETWEEN '2013-07-20' AND '2013-08-20'
            GROUP BY fk_users_recid, logtime
        ) logins
            ON logins.fk_users_recid = users.recid
GROUP BY recid, maxcontactdate, fk_staff_users_recid;
于 2013-08-20T11:32:21.953 回答