使用SQL 2005.我有三个表:会议,联系人和Meeting_Contacts。
会议表包含以下字段:Meeting_ID,Meeting_Name,Date_Start,Location
联系人有:Contact_ID,First_Name,Last_Name,Missed_Three_Days
Meeting_Contacts:Meeting_ID,Contact_ID
如果个人错过连续三天(周末除外),我需要更新“Missed_Three_Days”字段。
e.g。如果他错过星期五,星期一和星期二,“Missed_Three_Days字段将在星期二更新。
这是我到目前为止的地方......我被卡在哪里声明。
update contacts set missed_three_days = 'Missed 3 Days'
where ID not in
(select contact_ID from MEETINGS_CONTACTS mc
Join meetings m
on m.id = mc.meeting_id
join contacts c
on c.id = mc.contact_ID
where m.date_start ???)
我有一种感觉很明显......但我的思绪并没有指向今天的方向。
感谢您的帮助。
答案 0 :(得分:0)
从臀部拍摄你可以创建一个功能,测试每个错过的会议,以便错过第二次,然后第三次会议来自同一个人。像这样:
CREATE FUNCTION MissedThree
(
@pContact_ID int,
@pKeyDate Date
)
RETURNS Bit
AS
BEGIN
DECLARE @pReturnValue Bit = 0 /** FALSE UNTIL PROVEN OTHERWISE */
/** DID CONTACT MISS THIS MEETING? */
IF NOT Exists
(SELECT Meetings.Meeting_ID FROM
Meeting_Contacts INNER JOIN Meetings
ON Meetings.Meeting_ID = Meeting_Contacts.Meeting_ID
WHERE Contact_ID = @pContact_ID AND Meetings.Date_Start = @pKeyDate)
BEGIN
/** CHECK TO SEE IF NEXT WAS ALSO MISSED */
DECLARE @pMeetingTwo Date
SELECT @pMeetingTwo = MAX(Date_Start)
FROM Meetings WHERE Date_Start > @pKeyDate;
IF NOT Exists
(SELECT Meetings.Meeting_ID FROM
Meeting_Contacts INNER JOIN Meetings
ON Meetings.Meeting_ID = Meeting_Contacts.Meeting_ID
WHERE Contact_ID = @pContact_ID AND Meetings.Date_Start = @pMeetingTwo)
BEGIN
/** CHECKT TO SEE IF A THIRD CONSECUTIVE WAS MISSED */
DECLARE @pMeetingThree Date
SELECT @pMeetingThree = MAX(Date_Start)
FROM Meetings WHERE Date_Start > @pMeetingTwo;
IF NOT Exists
(SELECT Meetings.Meeting_ID FROM
Meeting_Contacts INNER JOIN Meetings
ON Meetings.Meeting_ID = Meeting_Contacts.Meeting_ID
WHERE Contact_ID = @pContact_ID AND Meetings.Date_Start = @pMeetingThree)
BEGIN
SET @pReturnValue = 1
END
END
END
RETURN @pReturnValue;
END
从那里你只需要运行一个查询来识别罪魁祸首。
SELECT Contact_ID, Start_Date FROM
Meeting_Contacts INNER JOIN Meetings
ON Meetings.Meeting_ID = Meeting_Contacts.Meeting_ID
WHERE dbo.MissedThree(Contact_ID, Start_Date) = 1
这里的好处是,它使用会议桌来确定会议的结果性质......而不是可能出现诸如周末,假日,非工作日等问题的日历。
我确信我能想出一个更优雅的解决方案,效率更高,但你必须付出比SO更多的钱:)。也许这会让你的创意果汁至少流淌。很多人都试图避免瘟疫之类的功能。
另外,你没有提到Sql版本,所以请注意,如果它不是2008,则需要为DateTime交换Date数据类型。
答案 1 :(得分:0)
我认为这样的事情可能会满足你的需求。
--select contacts who attended less than 3 of the last 3 meetings
SELECT
contacts.contact_id,
COUNT(meeting_contacts.meeting_id) as AttendedMeetings
FROM contacts
LEFT OUTER JOIN
( SELECT TOP 3
meetings.meeting_id
FROM meetings
ORDER BY meetings.date
) as Last3Meetings --the last 3 meetings and their attendees, regardless of when the meeting happened
LEFT OUTER JOIN meeting_contacts
ON meetings.meeting_id = meeting_contacts.meeting_id
AND contacts.contact_id = meeting_contacts.contact_id
HAVING COUNT(contacts.meeting_id) < 3
快乐的编码!