在Postgres找到min + 1

时间:2016-04-05 04:03:18

标签: sql postgresql greatest-n-per-group

大家好我有一个postgres表,其中包含事件列和序列列。每个事件可能有多个序列。例如:

Event  |   Sequence
a      |    1
a      |    4
a      |    5
b      |    1
b      |    2

现在我知道按事件选择min(序列)给出了最小序列。如何获得最小值后的下一个值。我希望这是有道理的。提前致谢。 我使用Postgres 9.3。

2 个答案:

答案 0 :(得分:2)

您可以 File inFile = new File("books.txt"); if (!inFile.isFile()) { return; } File tempFile = new File("books.txt" + "1"); BufferedReader br = new BufferedReader(new FileReader(inFile)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null; JTextField xField = new JTextField(10); JTextField yField = new JTextField(10); JPanel myPanel = new JPanel(); myPanel.add(new JLabel("Title:")); myPanel.add(xField); myPanel.add(Box.createHorizontalStrut(15)); // a spacer myPanel.add(new JLabel("ID:")); myPanel.add(yField); String removeLine = JOptionPane.showConfirmDialog(null, myPanel, "Remove", JOptionPane.OK_CANCEL_OPTION); if (removeLine == JOptionPane.OK_OPTION) { while ((line = br.readLine()) != null) { if (!line.trim().contains(removeLine)) { pw.println(line); pw.flush(); } } pw.close(); br.close(); //Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); return; } //Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) { System.out.println("Could not rename file"); } 使用ROW_NUMBER()分区,Event排序,以获得每个事件的第二低的序列号;

Sequence

An SQLfiddle to test with

答案 1 :(得分:0)

编辑稍微复杂一点,但是如果您需要一个不依赖ROW_NUMBER()的查询,请使用带有自联接的子查询来排除每个行的最小序列事件:

SELECT outer_query.Event, MIN(outer_query.Sequence) AS SecondMinSeq
FROM Table1 as outer_query
INNER JOIN (
    SELECT Table1.Event, MIN(Sequence) AS MinSeq
    FROM Table1
    GROUP BY Table1.Event
) AS min_sequences
ON outer_query.Event = min_sequences.Event AND outer_query.Sequence <> min_sequences.MinSeq
GROUP BY outer_query.Event

SQL小提琴:http://sqlfiddle.com/#!15/4438b/7