通过重复序列的SQL顺序

时间:2017-03-20 13:31:18

标签: sql

我在Oracle 11g中运行查询:

 public static String parseDateFormat(String incomingDate, String inputFormat, String outputFormat) {

        String finalDate = null;

        SimpleDateFormat input = new SimpleDateFormat(inputFormat); // server date format
        input.setTimeZone(TimeZone.getTimeZone(SERVER_TIMEZONE)); // timezone set in the server

        SimpleDateFormat output = new SimpleDateFormat(outputFormat); // format to which you want to convert
        output.setTimeZone(Constants.UTC_TIMEZONE);  // timezone to which you want to convert

        try {
            Date realDate = input.parse(incomingDate);
            finalDate = output.format(realDate);
        } catch (ParseException e) {
            Log.e("Error", e.getMessage(),e);
        }

        return finalDate;
    }

我希望将输出分组,如果已经存在序列ID,则将新结果移动到最后的新分组

SELECT id, sequence FROM objects WHERE parent=56;

Id.     Sequence
A           1
B           1
C           1
D           2
E           2
F           3

2 个答案:

答案 0 :(得分:1)

如果您的dbms支持窗口函数,请计算row_number并将其用于排序。

SELECT id,Sequence
FROM (
SELECT id, Sequence, ROW_NUMBER() OVER(PARTITION BY Sequence ORDER BY Id) as RN
FROM objects 
WHERE parent=56
) T
ORDER BY RN,Id

答案 1 :(得分:1)

我想指出,您可以将row_number()放入order by

select id, sequence
from objects
where parent = 56
order by row_number() over (partition by sequence order by id),
         sequence;