2012-09-26 51 views
6

我有兩個表,一個是任務列表。另一個包含這些任務的歷史價值。SQL Server:最大日期和內部聯接

我需要爲每一個檢查的最新事件的列表(及其說明),只要長爲Date_Executed小於當前日期時間減去TimeframeTimeFrame是小時內完成這項任務必須完成,格式化爲用於DATEADD)。但前提是他們有active = 1

表:檢查

Check_id description TimeFrame active 
1   Task One  -24  0 
2   Task Two  -24  0 
3   Task Forty -48  1 
4   Task Somehin -128  1 

表:事件

Event_id Check_id Comment  Date_Executed    User_Executed 
1   1   NULL  2012-09-18 16:10:44.917 admin 
2   1   NULL  2012-09-25 11:39:01.000 jeff 
3   4   Failed  2012-09-25 13:20:09.930 steve 
4   4   Half failed 2012-09-25 13:05:09.953 marsha 
5   2   NULL  2012-09-25 14:02:24.000 marsha 
6   3   NULL  2012-09-18 16:10:55.023 marsha 

最好的解決方案我至今是:

SELECT 
    a.[Date_Executed] 
    a.[Check_id], 
    a.[Comments], 
    b.[frequency], 
    b.[Check_id], 
    b.[description]  
FROM 
    [checksdb].[dbo].events as a, 
    [checksdb].[dbo].checks as b 
where 
    b.active = 1 
    and a.[Date_Executed] < = dateadd(HOUR,b.[frequency],GETDATE()) 
    and a.Check_id = b.Check_id 
order by Check_id, priority 

select MAX(date_Executed), Task_id from daily_check_events group by Task_id 

這兩個都沒有得到我所需要的,我真的可以用一些幫助。

+3

除了你已經試過了不給你你想要的結果的查詢,你可以告訴你想要的結果嗎?另外,[請停止使用'FROM table_a,table_b'語法](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins的.aspx)。 –

回答

8

由於您是SQL Server,它支持Common Table ExpressionWindow Function。試試這個,

WITH latestEvents 
AS 
(
    SELECT Event_id, Check_id, [Comment], Date_Executed, User_Executed, 
      ROW_NUMBER() OVER(PARTITION BY Check_ID ORDER BY DATE_Executed DESC) 
       AS RowNum 
    FROM events 
) 
SELECT a.[Check_id], a.[description], 
     b.[Date_Executed], b.[Comment] 
FROM checks a 
     INNER JOIN latestEvents b 
      on a.check_ID = b.check_ID 
WHERE b.RowNum = 1 AND 
     a.active = 1 
     -- other conditions here 

SQLFiddle Demo

上面的查詢將只支持Window Functions RDBMS工作。另外,使用下面的查詢工作在大多數RDBMS

SELECT a.Check_id, a.description, 
     c.Date_Executed, c.Comment 
FROM checks a 
     INNER JOIN 
     (
      SELECT check_id, MAX(Date_Executed) maxExecuted 
      FROM events 
      GROUP BY check_ID 
     ) b ON a.check_ID = b.check_ID 
     INNER JOIN events c 
      ON c.check_ID = b.check_ID AND 
      c.date_executed = b.maxExecuted 
WHERE a.active = 1 

SQLFiddle Demo

+0

謝謝。我最終使用了「Common Table Expression' Version」(對於遲到的回覆,不得不進行詳盡的測試)。 – flammable