SQL查询帮助:计算同一查询中前一行的最大值

时间:2018-01-12 05:36:37

标签: postgresql

我想找到每一行(其中B = C = D = 1),其先前行中的A的最大值(其中B = C = D = 1),排除其按时间顺序排序后的行。 / p>

表格中的数据如下所示:

+-------+-----+-----+-----+------+------+
|Grp id |  B  |  C  |  D  |  A   | time |
+-------+---- +-----+-----+------+------+
|  111  |  1  |  0  |  0  |  52  | t    | 
|  111  |  1  |  1  |  1  |  33  | t+1  | 
|  111  |  0  |  1  |  0  |  34  | t+2  | 
|  111  |  1  |  1  |  1  |  22  | t+3  | 
|  111  |  0  |  0  |  0  |  12  | t+4  | 
|  222  |  1  |  1  |  1  |  16  | t    | 
|  222  |  1  |  0  |  0  |  18  | t2+1 | 
|  222  |  1  |  1  |  0  |  13  | t2+2 | 
|  222  |  1  |  1  |  1  |  12  | t2+3 | 
|  222  |  1  |  1  |  1  |  09  | t2+4 | 
|  222  |  1  |  1  |  1  |  22  | t2+5 | 
|  222  |  1  |  1  |  1  |  19  | t2+6 | 
+-------+-----+-----+-----+------+------+

上表是以下查询的结果。它在左连接之后获得如下。根据我的项目要求,必须加入。

SELECT  Grp id, B, C, D, A, time, xxx
FROM "DCR" dcr 
    LEFT JOIN "DCM" dcm ON "Id" = dcm."DCRID"
    LEFT JOIN "DC" dc ON dc."Id" = dcm."DCID" 
ORDER BY dcr."time"

结果列需要根据上面提到的公式I进行评估。它需要在同一过程中计算,因为我们只需要考虑它以前的行。上面的xxx需要用子查询/语句替换才能获得结果。

结果表应如下所示:

+-------+-----+-----+-----+------+------+------+
|Grp id |  B  |  C  |  D  |  A   | time |Result|  
+-------+---- +-----+-----+------+------+------+
|  111  |  1  |  0  |  0  |  52  | t    |  -   | 
|  111  |  1  |  1  |  1  |  33  | t+1  |  -   |
|  111  |  1  |  1  |  1  |  34  | t+2  |  33  |
|  111  |  1  |  1  |  1  |  22  | t+3  |  34  |
|  111  |  0  |  0  |  0  |  12  | t+4  |  -   |
|  222  |  1  |  1  |  1  |  16  | t    |  -   |
|  222  |  1  |  0  |  0  |  18  | t2+1 |  -   |
|  222  |  1  |  1  |  0  |  13  | t2+2 |  -   |
|  222  |  1  |  1  |  1  |  12  | t2+3 |  16  |
|  222  |  1  |  1  |  1  |  09  | t2+4 |  16  |
|  222  |  1  |  1  |  1  |  22  | t2+5 |  16  |
|  222  |  1  |  1  |  1  |  19  | t2+6 |  22  |
+-------+-----+-----+-----+------+------+------+

1 个答案:

答案 0 :(得分:0)

可以使用窗口函数计算列:

CASE WHEN b = 1 AND c = 1 AND d = 1
     THEN max(a) FILTER (WHERE b = 1 AND c = 1 AND d = 1)
                 OVER (PARTITION BY "grp id"
                       ORDER BY time
                       ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
     ELSE NULL
END

我没有测试过。