在Access中的子查询中使用MAX函数

时间:2014-04-09 14:25:41

标签: sql

在Microsoft Access中,我正在查询四个表中的数据,并且我正在使用MAX函数来显示最新的记录。下面的代码有效但它使用了两个链接在一起的查询。通过使用下面显示完整代码的子查询,代码需要一个小时才能运行,这就是我使用两个查询的原因。有没有更好的方法呢?

QUERY 1

SELECT 
    a.office_id AS ofid, 
    rc.recorder_id AS recorder, 
    a.cust_name, 
    r.account_id, 
    rc.lpc_phone, 
    rc.device_serial, 
    rc.device_mfg, 
    rc.device_type 
INTO RDS_INFO
FROM MaxDates 
INNER JOIN (status AS s INNER JOIN ((config_recorder AS rc INNER JOIN recorders AS r ON rc.recorder_id = r.recorder_id) 
INNER JOIN accounts AS a ON r.account_id = a.account_id) ON s.status = rc.row_status) ON (MaxDates.MaxOftrans_datetime = rc.trans_datetime) AND (MaxDates.recorder_id = rc.recorder_id)
WHERE (((rc.lpc_phone) Is Not Null 
And (rc.lpc_phone)<>" " 
And (rc.lpc_phone) Not Like "#,*") 
AND ((rc.call_mode)="AN") 
AND ((rc.row_status)=3 
Or (rc.row_status)=11));

MaxDates查询:

SELECT 
    config_recorder.recorder_id, 
    Max(config_recorder.trans_datetime) AS MaxOftrans_datetime
FROM config_recorder
GROUP BY config_recorder.recorder_id;

与子查询一起使用的代码:

        SELECT 
            a.cycle AS cyc, 
            a.office_id AS ofid, 
            rc.recorder_id AS recorder, 
            a.cust_name, 
            r.account_id, 
            rc.lpc_phone, 
            rc.device_serial, 
            rc.device_mfg, 
            rc.device_type 
        INTO Test
FROM config_recorder AS rc, status AS s, recorders AS r, accounts AS a
WHERE rc.recorder_id=r.recorder_id
AND r.account_id=a.account_id 
AND ((rc.lpc_phone Is Not Null) 
AND (rc.lpc_phone<>" ") 
AND (rc.lpc_phone Not Like "#,*")) 
AND ((rc.call_mode="AN") 
AND (rc.row_status=s.status) 
AND ((rc.row_status="3") 
Or (rc.row_status="11"))) 
AND (rc.trans_datetime=(select max(r2.trans_datetime) from config_recorder r2 where r2.recorder_id = rc.recorder_id));

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以考虑将子查询更改为内联视图,然后将其与其他表连接,如下所示:

SELECT 
a.office_id AS ofid, 
rc.recorder_id AS recorder, 
a.cust_name, 
r.account_id, 
rc.lpc_phone, 
rc.device_serial, 
rc.device_mfg, 
rc.device_type 
INTO RDS_INFO
FROM status AS s 
INNER JOIN 
(config_recorder AS rc INNER JOIN recorders AS r ON rc.recorder_id = r.recorder_id)
ON s.status = rc.row_status
INNER JOIN accounts AS a 
ON r.account_id = a.account_id
INNER JOIN 
(SELECT 
    config_recorder.recorder_id, 
    Max(config_recorder.trans_datetime) AS MaxOftrans_datetime
FROM config_recorder
GROUP BY config_recorder.recorder_id) MaxDates 
ON (MaxDates.MaxOftrans_datetime = rc.trans_datetime) AND (MaxDates.recorder_id = rc.recorder_id)
WHERE (((rc.lpc_phone) Is Not Null 
And (rc.lpc_phone)<>" " 
And (rc.lpc_phone) Not Like "#,*") 
AND ((rc.call_mode)="AN") 
AND ((rc.row_status)=3 
Or (rc.row_status)=11));

参考文献:

  1. A related question on SO
  2. Inline Views Versus Temp Tables on MSDN Magazine