复杂的顺序By - Suborder by Query

时间:2013-03-10 19:46:23

标签: mysql sql

我需要为下面提到的表结构执行汇总计算,我需要通过“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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

假设您要将第一个sequence=1与第一个sequence=2和第一个sequence=3组合在一起,同样第二个1与第二个2组合在一起第二个3等等(使用pk_id作为订单),您可以使用变量赋值来编号sequence,然后使用生成的数字进行排序。

这就是我的意思:

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
;

可以测试此查询at SQL Fiddle