SQL - 选择多个行范围,但跳过范围之间的行

时间:2017-05-19 18:33:24

标签: sql postgresql

例如,我有:

enter image description here

但我需要:

enter image description here

我需要做的是选择多个范围,其中每个范围从“AppStart”开始,并在第一次遇到“PossibleEnd”时结束。

我正在使用PostgreSQL 9.3。我可以为我需要的最终结果做转轴,它选择了我无法弄清楚的范围。

2 个答案:

答案 0 :(得分:0)

好吧,这个查询会给你所有的开始

 SELECT row_num 
 FROM table_name_you_did_not_say
 WHERE event='AppStart'

这就是你的结局

 SELECT row_num 
 FROM table_name_you_did_not_say
 WHERE event='PossibleEnd'

您要做的是根据行排序加入这些 - 您可以使用窗口函数来执行此操作:

 SELECT Start.row_num as StartNumber, Ends.row_number as EndNumber
 FROM (
   SELECT row_num, ROW_NUMBER() OVER (ORDER BY row_num ACC) as RN
   FROM table_name_you_did_not_say
   WHERE event='AppStart'
 ) Starts
 JOIN (
   SELECT row_num, ROW_NUMBER() OVER (ORDER BY row_num ACC) as RN
   FROM table_name_you_did_not_say
   WHERE event='PossibleEnd'
 ) Ends ON Starts.RN = Ends.RN

答案 1 :(得分:0)

Hogan的答案很好,但如果窗口函数对你来说太复杂了,这里有一个更简单的解决方案:

$('.launch').click(function(){
  $(this).next().find("a:first-of-type").trigger('click');
});

一些解释:

  • 选择所有起始索引和所有结束索引
  • 加入这两个子查询,条件是结尾必须在开始之后
  • 将起始索引分组以获得最小结束点

要获取“中间的列”,请使用

围绕上述查询
SELECT
    start_row,
    MIN(end_row) AS end_row
FROM
    (SELECT
        row_num AS start_row
    FROM
        table_name
    WHERE
        event = 'AppStart'
    ) AS starts
    ,
    (SELECT
        row_num AS end_row
    FROM
        table_name
    WHERE
        event = 'PossibleEnd'
    ) AS ends
WHERE
    end_row > start_row
GROUP BY
    start_row

结果是:

SELECT
    start_row,
    (SELECT
        array_agg(row_num)
    FROM
        table_name
    WHERE
        row_num > start_row AND
        row_num < end_row
    ) AS columns_in_between,
    end_row
FROM (
    ... the above query goes here
) AS X