(MySql引擎) 我有一张桌子记录了工作人员和俱乐部成员之间的联系,称为“联系人”。 我需要通过比较会员在整个时间段之前和之后记录的平均次数来了解最新联系是否对会员出席产生了积极影响。 登录存储在登录表中。 用户信息存储在users表中。
以下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
答案 0 :(得分:2)
您可以使用条件计数(计数语句中的CASE WHEN ..)
来执行此操作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;