SQL Top和Join

时间:2012-08-29 18:34:35

标签: sql join sybase-ase

业务规则:我们只能每90天为后续事件收费。在上一个事件发生后不到90天内发生的任何事件都无法结算,但需要进行记录。

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

事件在表事件中有一个event_id和一个event_date。 Event_id是表event_bill中的外键,它具有该帐单的submitted_date。 对于每个客户,事件都有一个外键customer_id,因此客户可以在任何时间段内拥有多个事件。

鉴于当前的event_id和customer_id,我正在尝试获取最近一次事件的submitted_date。

这是我尝试过的:

    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

有人能给我一个更好的方法吗?

3 个答案:

答案 0 :(得分: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
   )

答案 1 :(得分: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

答案 2 :(得分: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,然后将其用于连接。