Postgres集团和按范围排序(具体值)

时间:2017-09-04 20:36:57

标签: sql postgresql-9.4

我有一张这样的表:

id           simcard          simcard_order
80769   56407503370245588410    1
80788   66329183922439284822    2
80803   20993658565113174305    0
80804   81781641934100313243    4
80852   71560493627263868232    3
80784   23739383536995189713    1
80793   42702512646659519628    2
80805   17990699721985463506    0
80832   08525531276567944345    4
80854   74478849586042090832    3
80786   22535328208807554315    1
80812   34317440773382930807    0
80826   36103390459816949722    2
80858   15439885499080289130    3
80862   26786481240939036248    4
80792   59566921916027957512    1
80813   98968026512101636608    0
80835   65834894114116066528    2
80864   17764015687751814947    4
80882   41427844162545991837    3
80887   41587969946566907740    4
80891   46059625228552654737    3
80824   76381392106884963712    1
80863   77385361462191701926    2
80868   46607630719285200008    0
80892   08860583551940471945    4
80899   85443153649210377733    3
80934   90908807112484733323    2
80937   25660906025678471304    0
80967   34298088103509862330    3

列simcard_order具有从0到4的重复值。

我想订购这样的表格:

id  simcard simcard_order
80769   56407503370245588410    0
80788   66329183922439284822    1
80803   20993658565113174305    2
80804   81781641934100313243    3
80852   71560493627263868232    4
80784   23739383536995189713    0
80793   42702512646659519628    1
80805   17990699721985463506    2
80832   08525531276567944345    3
80854   74478849586042090832    4
80786   22535328208807554315    0
80812   34317440773382930807    1
80826   36103390459816949722    2
80858   15439885499080289130    3
80862   26786481240939036248    4
....

依此类推......所以在这种情况下,我有3组(0,1,2,3,4) 订单总是必须是0,1,2,3,4。

我已经使用过这个sql,但它无法正常工作:

SELECT id, simcard, simcard_order
FROM tmp_pending_simcards
WHERE tmp_pending_simcards.simcard_order IN (0, 1, 2, 3, 4)
ORDER BY (0, 1, 2, 3, 4)

1 个答案:

答案 0 :(得分:3)

如果我理解正确:

SELECT id, simcard, simcard_order
FROM tmp_pending_simcards tps
WHERE tps.simcard_order IN (0, 1, 2, 3, 4)
ORDER BY ROW_NUMBER() OVER (PARTITION BY tps.simcard_order),
         tps.simcard_order;

通常情况下,您会ORDER BY作为ROW_NUMBER()的一部分,但Postgres不需要它。