计算日期

时间:2013-02-08 02:15:40

标签: sql sql-server

我遇到了这个问题:客户列表中包含下一次计划的,重复出现的约会,即年度,月度或季度。

我拥有的表\列是:

customer
   customer_ID
service
   customer_ID
   service_RecID
Resource
   service_RecID
   Recurrence_RecID
   Date_Time_Start
Recurrence
   Recurrence_RecID
   RecurType
   RecurInterval
   DaysOfWeek
   AbsDayNbr
   SelectInterval

对其进行建模,以便在设置计划时,date_start_time是第一次重复发生的约会发生的日期。实施例

Recurrence_RecID = 10
RecurType = m (could be y, or d as well for yearly or daily)
RecurInterval = 6 (if recurType = y, this would mean every 6 years)

鉴于系统每晚都会生成这些内容,我如何编写查询来计算每个客户的下一个预约?我最初想过使用Resource.Date_Time_Start并直接循环直到变量nextAppointment> = today(),但是在SQL中运行循环是不错的做法?

如果需要更多信息,请告诉我。非常感谢!

编辑:我会制作一个方形的。

1 个答案:

答案 0 :(得分:1)

我建议使用子查询而不是循环。这种方式效率更高。这可能不准确,但有点像......

SELECT 
    *
FROM
(      
SELECT
    customer.customer_id,
    service.service_RecID,
    Resource.Date_Time_Start,
    Recurrence.Recurrence_RecID,
    RecurType,
    RecurInterval,
    DaysOfWeek,
    AbsDayNbr,
    SelectInterval,
    NextAppointmentDate=
    CASE 
        WHEN RecurType='m' THEN DATEADD(MONTH,RecurInterval,Resource.Date_Time_Start)
        WHEN RecurType='y' THEN DATEADD(YEAR,RecurInterval,Resource.Date_Time_Start)
    ELSE 
        NULL
    END        
FROM
    Recurrence
    INNER JOIN Resource ON Resource.Recurrence_RecID=Recurrence.Recurrence_RecID
    INNER JOIN service ON service.service_RecID=Resource.service_RecID
    INNER JOIN customer ON customer.customer_ID=service.customerID
)AS X
WHERE
    NextAppointmentDate>=GETDATE()
ORDER BY Fields...