0

业务规则:我们只能每 90 天为后续事件计费。任何发生在前一个事件之后不到 90 天的事件都不能计费,但需要记录下来。

用户要求:他们希望在提交当前事件账单的选项卡上查看上次事件账单提交的日期,以直观地提示提交账单是否值得。

事件在表事件中有一个 event_id 和一个 event_date。event_id 是表 event_bill 中的外键,其中包含账单的提交日期。事件对于每个客户都有一个外键 customer_id,因此一个客户可以在任何时间段内有多个事件。

鉴于当前的 event_id 和 customer_id,我正在尝试获取最近一次活动的提交日期。

这是我尝试过的:

    SELECT TOP 1 (event_id) as prev_event_id
    INTO #tmp
    FROM  event 
    WHERE customer_id = @custID
    AND event_type = 'Followup'
    AND event_id < @eventID 
    ORDER BY event_date DESC

    SELECT eb.submitted_date
    FROM event_bill eb
    JOIN #tmp
    ON eb.event_id = #tmp.prev_event_id

    DROP TABLE #tmp

这一切都很好,但是我的应用程序的数据库权限不允许创建临时表。

在没有临时表的尝试中,我得到了无法在派生表中使用 ORDER BY 的错误,但我需要确保我获得该客户当前事件之前的最后一个事件:

    SELECT eb.submitted_date
    FROM event_bill eb
    JOIN
    (
    SELECT TOP 1 (event_id) as prev_event_id
    FROM  event 
    WHERE customer_id = @custID
    AND event_type = 'Followup'
    AND event_id < @eventID 
    ORDER BY event_date DESC
    ) x
    ON eb.event_id = x.prev_event_id

谁能给我一个更好的方法来解决这个问题?

4

3 回答 3

0

尝试这个 :)

SELECT eb.submitted_date
FROM event_bill eb
WHERE
  eb.event_id IN (
    SELECT event.event_id 
    FROM event 
    WHERE 
      event.customer_id = @custID 
      AND event.event_type = 'Followup'
      AND event.event_id < @eventID
    ORDER BY event_date DESC
     LIMIT 1
   )
于 2012-08-29T18:47:04.707 回答
0

也许它会帮助你

 SELECT eb.submitted_date
    FROM event_bill eb
    JOIN
    (
    SELECT event_id as prev_event_id
    FROM  event 
    WHERE customer_id = @custID
    AND event_type = 'Followup'
    AND event_id < @eventID 
    and event_date = 
    (
      select max(event_date)
      FROM  event 
      WHERE customer_id = @custID
      AND event_type = 'Followup'
      AND event_id < @eventID 
    )
    ) x
    ON eb.event_id = x.prev_event_id
于 2012-08-29T18:47:56.203 回答
0

我认为 ORDER BY 会被顶部接受。如果没有,您可以这样做:

 SELECT eb.submitted_date
 FROM event_bill eb JOIN
      event e
      on eb.event_id = e.event_id join
      (SELECT customer_id, MAX(eventdate) as maxdate
       FROM  event
       WHERE customer_id = @custID AND
            event_type = 'Followup' AND
            event_id < @eventID
       group by customer_id
      ) md
     ON e.customer_id = md.customer_id and
        eb.event_date = md.maxdate

这会计算 maxdate,然后将其用于连接。

于 2012-08-29T18:48:13.197 回答