2

我想按列“值”对表中的行进行排序,其中字段 =“订单”,按 ObjectId 对行进行分组:

 Id | ObjectId | Field | Value
------------------------------
 1  |    1     | size  |  big
 2  |    1     | order |   2   //unsorted
 3  |    2     | size  | small
 4  |    2     | order |   1   //unsorted
 5  |    3     | size  | medium
 6  |    3     | order |   3   //unsorted

预期结果:

 Id | ObjectId | Field | Value
------------------------------
 3  |    2     | size  | small
 4  |    2     | order |   1   //sorted
 1  |    1     | size  |  big
 2  |    1     | order |   2   //sorted
 5  |    3     | size  | medium
 6  |    3     | order |   3   //sorted
4

1 回答 1

0

您需要先加入大小的字段值:

select t.*
from t join
     (select t.object_id, max(case when field = 'order' then value end) as ordering
      from t
      group by t.object_id
     ) tsum
     on t.object_id = tsum.object_id
order by tsum.ordering, t.object_id, id;

这将相同的“排序”分配给具有相同object_id.

于 2013-07-01T11:22:32.180 回答