1

我需要对下面提到的表结构进行汇总计算,因为我需要按“sessionId”排序,按“sequenceId”排序。特定会话可以有一个或多个序列。每个序列都从一个开始并按顺序前进。主键和流序列可能不是串联的。

表>>

pk_id  session-id    sequence   some_other columns
  1    AAAAAAAA          1        blah-blah-blah
  2    AAAAAAAA          2        blah-blah-blah 
  3    AAAAAAAA          3        blah-blah-blah
  4    AAAAAAAA          2        blah-blah-blah
  5    AAAAAAAA          1        blah-blah-blah
  6    AAAAAAAA          3        blah-blah-blah
  7    AAAAAAAA          3        blah-blah-blah
  8    AAAAAAAA          2        blah-blah-blah
  9    AAAAAAAA          1        blah-blah-blah

我需要订购

 pk_id  session-id    sequence   some_other columns
  1    AAAAAAAA          1        blah-blah-blah
  2    AAAAAAAA          2        blah-blah-blah 
  3    AAAAAAAA          3        blah-blah-blah

  5    AAAAAAAA          1        blah-blah-blah
  4    AAAAAAAA          2        blah-blah-blah
  6    AAAAAAAA          3        blah-blah-blah

  9    AAAAAAAA          1        blah-blah-blah
  8    AAAAAAAA          2        blah-blah-blah
  7    AAAAAAAA          3        blah-blah-blah

任何帮助,将不胜感激。

4

1 回答 1

3

Assuming you want to group together the first sequence=1 with the first sequence=2 and the first sequence=3, and similarly the second 1 with the second 2 and second 3 and so on (using pk_id as the order), you could use variable assignment to number sequence values, then use the resulting numbers for sorting.

This is what I mean:

SELECT
  pk_id,
  session_id,
  sequence,
  some_other_column
FROM (
  SELECT
    @row := (session_id = @sid AND sequence = @seq) * @row + 1 AS row,
    pk_id,
    @sid := session_id AS session_id,
    @seq := sequence AS sequence,
    some_other_column
  FROM
    atable,
    (SELECT @row := 0, @sid := '', @seq := 0) AS s
  ORDER BY
    session_id,
    sequence,
    pk_id
) AS s
ORDER BY
  session_id,
  row,
  sequence
;

This query can be tested at SQL Fiddle.

于 2013-03-10T23:02:08.597 回答