筛选相关子查询时值消失

时间:2019-03-07 21:37:02

标签: sql ms-access where-clause correlated-subquery running-total

这个问题与我最近here提供的答案有关。


设置

使用MS Access 2007。

假设我有一个名为mytable的表,该表由三个字段组成:

  • id长整数自动编号(PK)
  • type文字
  • num长整数

具有以下示例数据:

+----+------+-----+
| id | type | num |
+----+------+-----+
|  1 | A    |  10 |
|  2 | A    |  20 |
|  3 | A    |  30 |
|  4 | B    |  40 |
|  5 | B    |  50 |
|  6 | B    |  60 |
|  7 | C    |  70 |
|  8 | C    |  80 |
|  9 | C    |  90 |
| 10 | D    | 100 |
+----+------+-----+

类似于链接的答案,我想输出三个字段,每个type值的运行总计,运行总计的值限制为最大100,我可能使用相关的子查询,如下所示:

select q.* from
(
    select t.id, t.type, t.num, 
        (
            select sum(u.num)
            from mytable u where u.type = t.type and u.id <= t.id
        ) as rt
    from mytable t
) q
where q.rt < 100

这将产生预期的结果:

+----+------+-----+----+
| id | type | num | rt |
+----+------+-----+----+
|  1 | A    |  10 | 10 |
|  2 | A    |  20 | 30 |
|  3 | A    |  30 | 60 |
|  4 | B    |  40 | 40 |
|  5 | B    |  50 | 90 |
|  7 | C    |  70 | 70 |
+----+------+-----+----+

观察

现在假设我希望过滤结果以仅显示type like "[AB]"的那些值。

如果我使用以下任一查询:

select q.* from
(
    select t.id, t.type, t.num, 
        (
            select sum(u.num)
            from mytable u where u.type = t.type and u.id <= t.id
        ) as rt
    from mytable t
    where t.type like "[AB]"
) q
where q.rt < 100
select q.* from
(
    select t.id, t.type, t.num, 
        (
            select sum(u.num)
            from mytable u where u.type = t.type and u.id <= t.id
        ) as rt
    from mytable t
) q
where q.rt < 100 and q.type like "[AB]"

结果将按预期进行过滤,但是rt(运行总计)列中的值消失了:

+----+------+-----+----+
| id | type | num | rt |
+----+------+-----+----+
|  1 | A    |  10 |    |
|  2 | A    |  20 |    |
|  3 | A    |  30 |    |
|  4 | B    |  40 |    |
|  5 | B    |  50 |    |
+----+------+-----+----+

问题

为什么过滤器会使相关子查询返回的值消失?


感谢您阅读我的问题的时间,并感谢您提供任何建议。

0 个答案:

没有答案