我有一个表格,其中包含有关联系人呼叫尝试的信息。相关领域如下:
Contact Date Result
John Smith 1/8/2013 VM
John Smith 1/9/2013 VM
John Smith 1/10/2013 Busy Signal
John Smith 1/11/2013 Hang Up <--- Connect
Jane Smith 1/8/2013 VM
Jane Smith 1/9/2013 Scheduled Call Back <--- Connect
Jane Smith 1/10/2013 VM
John Doe 1/8/2013 Not Interested <--- Connect
Jane Doe 1/8/2013 Busy Signal
Jane Doe 1/9/2013 Busy Signal
Jane Doe 1/10/2013 Busy Signal
我正在尝试计算尝试次数,直到通过联系人连接(而不是第一次连接后的任何尝试),或者到目前为止没有连接的尝试次数,我正在麻烦。在这种情况下表示连接的结果将是挂机,预定回拨和不感兴趣。
我想要的是:
Contact Attempts
John Smith 4
Jane Smith 2
John Doe 1
Jane Doe 3
有办法做到这一点吗?任何帮助将不胜感激。
答案 0 :(得分:2)
您需要考虑使用GROUP BY
:
SELECT Contact, COUNT(*) Attempts
FROM Contacts
WHERE Result NOT IN ('Hang Up','Scheduled Call Back','Not Interested')
GROUP BY Contact
- 编辑
没有意识到OP的要求。在他接受另一个答案之前无法完成这个......
祝你好运。答案 1 :(得分:1)
对于MySQL:
SELECT
t.Contact, COUNT(*) AS Attempts
FROM
tableX AS t
JOIN
( SELECT DISTINCT contact
FROM tableX
) AS d
LEFT JOIN
( SELECT contact,
MIN(date) AS date
FROM tableX
WHERE result IN ('Hang Up', 'Scheduled Call Back', 'Not Interested')
GROUP BY contact
) AS g
ON d.contact = g.contact
ON t.contact = d.contact
AND t.date <= COALESCE(g.date, '9999-12-31')
GROUP BY
t.contact ;