Arrange my result in select query of postgresql?

时间:2016-02-03 02:40:44

标签: sql postgresql

I have a query:

select c1,q1,c2,q2,c3,q3,c4,q4 from mxm

The result is:

c1    q1   c2     q2    c3     q3    c4      q4   
9103  4    9114   3.3   9197   1.9   B9151   3000 
9103  15   9107   8.6   9118   8.3   B9100   130.6
9103  3.6  9114   0.6   9197   1.1   B9151   5000

But I want this output like:

9103  4
9114  3.3   
9197  1.9   
B9151 3000 
9103   15   
9107   8.6   
9118   8.3   
B9100  130.6

and so on .... Is this possible in postgresql?

1 个答案:

答案 0 :(得分:0)

If you want them in that order, it is a bit tricky. Assuming you have no appropriate id in mxm for identifying the rows in order:

with t as (
      select row_number() over (order by ??) as seqnum, mxm.*
      from mxm
)
select c, q
from ((select c1, q1, seqnum, 1 as ordering from t) union all
      (select c2, q2, seqnum, 2 from t) union all
      (select c3, q3, seqnum, 3 from t) union all
      (select c4, q4, seqnum, 4 from t)
     ) cq
order by seqnum, ordering;

The ?? is for the column that specifies the original ordering for the records.