MS Access中的等效查询

时间:2012-08-22 05:39:31

标签: ms-access

以下是在ORACLE中写入的查询,以给出前一行,最后给出的输出。 如何在MS Access特别是ROWNUM部分的ORACLE查询下面框架..感谢您的输入

orcl> WITH d
  2       AS (SELECT ROWNUM rn,
  3                  dname,
  4                  deptno
  5           FROM   (SELECT dname,
  6                          deptno
  7                   FROM   dept
  8                   ORDER  BY dname)),
  9       e
 10       AS (SELECT ROWNUM + 1 rn,
 11                  dname,
 12                  deptno
 13           FROM   (SELECT dname,
 14                          deptno
 15                   FROM   dept
 16                   ORDER  BY dname))
 17  SELECT rn,
 18         d.dname,
 19         d.deptno this_row,
 20         e.deptno previous_row
 21  FROM   d
 22         left outer join e USING (rn)
 23  ORDER  BY dname;

    RN DNAME            THIS_ROW      previous_ROW

     1 ACCOUNTING             10
     2 OPERATIONS             40           10
     3 RESEARCH               20           40
     4 SALES                  30           20

1 个答案:

答案 0 :(得分:2)

Access SQL与查询使用的某些Oracle功能没有直接对应关系,因此您无法“”转换为Access。相反,你必须从头开始重写它。

您可以使用DMax()表达式返回“上一个”dname

SELECT
    dname,
    deptno AS this_row,
    DMax("dname", "dept", "dname < '" & [dname] & "'")
        AS previous_dname
FROM dept;

该查询返回此结果集:

dname       this_row previous_dname
ACCOUNTING        10
OPERATIONS        40 ACCOUNTING
RESEARCH          20 OPERATIONS
SALES             30 RESEARCH

然后将结果集连接到dept表,并将连接基于previous_dname = dname

SELECT
    d1.dname,
    d1.this_row,
    d2.deptno AS previous_row
FROM
    (
        SELECT
            dname,
            deptno AS this_row,
            DMax("dname", "dept", "dname < '" & [dname] & "'")
                AS previous_dname
        FROM dept
    ) AS d1
    LEFT JOIN dept AS d2
    ON d1.previous_dname = d2.dname
ORDER BY d1.dname;

我省略了rn(ROWNUM)列,因为使用此方法的连接不需要它。但是,如果由于某些其他原因仍然需要/想要它,可以使用DCount()表达式派生它。

SELECT
    d1.rn
    d1.dname,
    d1.this_row,
    d2.deptno AS previous_row
FROM
    (
        SELECT
            DCount("*", "dept", "dname <= '" & [dname] & "'")
                AS rn
            dname,
            deptno AS this_row,
            DMax("dname", "dept", "dname < '" & [dname] & "'")
                AS previous_dname
        FROM dept
    ) AS d1
    LEFT JOIN dept AS d2
    ON d1.previous_dname = d2.dname
ORDER BY d1.dname;