SQLite - 最大(列)的棘手查询

时间:2014-02-05 09:48:52

标签: java sql sqlite

我用SQL Fiddle构建了一个架构:

SQL Fiddle - Schema

我们在 testtable 中有这些列:

  1. id [int]作为主键(未使用 - >不重要
  2. 结束 [int] - 如果将新流写入表中,则除最后一次的值都为“0”且最后一位的值为“1”。这是指输入流在这里完成。
  3. time_abs [int] - 绝对时间(例如以分钟为单位)。
  4. r_m [双倍] - 随着时间的推移而升级的质量率
  5. T_r [double] - 无所谓
  6. 类型 [字符串] - 此处也无所谓
  7. x0 [字符串] - 离开(例如水来自哪里?)
  8. x1 [字符串] - 目的地(例如水流入哪里?)
  9. 正如您在SQL Fiddle Schema中所看到的,我们在某个特定时间查询每个质量,如下所示:

    SELECT
    (SELECT (SELECT total(r_m) 
             FROM testtable 
             WHERE time_abs=11 AND end=0 AND x1='vessel2') + 
            (SELECT total(r_m) 
             FROM testtable 
             WHERE end=1 AND time_abs <=11 AND x1='vessel2')
    )
    -
    (SELECT (SELECT total(r_m) 
             FROM testtable 
             WHERE time_abs=11 AND end=0 AND x0='vessel2') + 
            (SELECT total(r_m) 
             FROM testtable 
              WHERE end=1 AND time_abs <=11 AND x0='vessel2')
    )
    

    效果很好而且速度很快。

    但我们现在要查询的是 r_m 最大 时间范围

    E.g。 伪代码

    SELECT max(total(r_m)) 
    WHERE time_abs BETWEEN 1 AND 30 & SELECT time_abs WHERE r_m=max ...
    

    这个伪查询的结果是(123,13-24)( max(总质量) 时间跨度总计mass = max )(在SQL Fiddle Schema中手动检查)。

    有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是一个查询,显示血管2中的水平在5到26秒之间:

select  times.time_abs
,       sum(
        case when x1 = 'vessel2' and ([end] = 1 or times.time_abs = tt.time_abs)
             then r_m else 0 end - 
        case when x0 = 'vessel2' and ([end] = 1 or times.time_abs = tt.time_abs) 
             then r_m else 0 end
        ) as lvl
from    (
        select  distinct time_abs
        from    testtable
        where   time_abs between 5 and 26
        ) times
join    testtable tt
on      tt.time_abs <= times.time_abs 
        and 'vessel2' in (tt.x0, tt.x1)
group by
        times.time_abs

要显示最大值,您可以:

select  max(lvl) 
from    (
        ...query from above...
        ) as SubQueryAlias

Live example at SQL Fiddle.