Ms-Access-2010

查詢:MS Access 2010 中兩個欄位的唯一組合的最新記錄

  • August 7, 2016

我正在嘗試對一些交通量數據進行查詢,但遇到了一些麻煩。我想提取每個路段的最新數據,但事實證明這比預期的要復雜。

這是我正在使用的數據的範例:

S_ID | DATE      | DIRECTION | AADT
1001 | 9/16/2013 | North     | 700
1001 | 9/16/2013 | South     | 600
1001 | 1/30/2011 | NULL      | 1093
1001 | 2/31/2009 | NULL      | 1091
1211 | 1/17/2012 | NULL      | 945
1235 | 1/23/2014 | North     | 500
1235 | 6/19/2014 | South     | 350
1235 | 5/10/2011 | South     | 354
1235 | 5/10/2011 | North     | 399
1301 | 9/16/2013 | East      | 700
1301 | 4/16/2012 | West      | 600
1301 | 1/30/2014 | NULL      | 1093

我對返回每個 SectionID 和方向的最新 AADT(年平均每日流量)值感興趣。在上面的數據中,我希望返回以下值:

S_ID | DATE      | DIRECTION | AADT
1001 | 9/16/2013 | North     | 700
1001 | 9/16/2013 | South     | 600
1211 | 1/17/2012 | NULL      | 945
1235 | 1/23/2014 | North     | 500
1235 | 6/19/2014 | South     | 350
1301 | 1/30/2014 | NULL      | 1093

我有以下程式碼:

SELECT  a.*
INTO    recent_data
FROM    primarytrafficcountdata a
INNER
JOIN    (
       SELECT  section_id,
               direction,
               MAX(date) AS maxdate
       FROM    primarytrafficcountdata
       WHERE   YEAR(date) <= 2014
       AND     YEAR(date) >= 2011
       GROUP BY
               section_id,
               direction
       ) groupeda
ON      (a.section_id = groupeda.section_id
AND      a.direction = groupeda.direction
AND      a.date = groupeda.maxdate)
OR      (a.section_id = groupeda.section_id
AND      a.direction IS NULL and groupeda.direction IS NULL
AND      a.date = groupeda.maxdate)
;

但這會返回:

S_ID | DATE      | DIRECTION | AADT
1001 | 9/16/2013 | North     | 700
1001 | 9/16/2013 | South     | 600
1001 | 1/30/2011 | NULL      | 1093
1211 | 1/17/2012 | NULL      | 945
1235 | 1/23/2014 | North     | 500
1235 | 6/19/2014 | South     | 350
1301 | 9/16/2013 | East      | 700
1301 | 4/16/2012 | West      | 600
1301 | 1/30/2014 | NULL      | 1093

這是我想要的最新日期,但我想消除北/南或東/西方向,並且僅在 NULL 方向較新時使用 NULL 方向,反之亦然,當北/南或東/ West 是最新的記錄。

有誰知道我會怎麼做?

我正在使用 Microsoft Access 2010。

嘗試這個:

SELECT  a.* INTO recent_data 
FROM primarytrafficcountdata a 
INNER JOIN (SELECT section_id,MAX(date) AS maxdate 
             FROM primarytrafficcountdata 
             WHERE YEAR(date) <= 2014 AND YEAR(date) >= 2011 
            GROUP BY section_id) groupeda 
ON (a.section_id = groupeda.section_id AND a.date = groupeda.maxdate);

引用自:https://dba.stackexchange.com/questions/145919