Search code examples
sqlms-access

How to Get 2 different data colums from same table


I have this table:

CODE SUBCODE VALUE
1 120 5130
1 100 1000
1 983 -123
2 100 598123
2 713 -7123
2 813 -78123
3 110 5123
3 130 -8976
4 150 951
4 123 -6891
5 160 513
5 512 -213

How can I get list of all positive data columns on the one side and other side with all negative data?

SUBCODE VALUE SUBCODE VALUE
100 598123 813 -78123
120 5130 130 -8976
110 5123 713 -7123
100 1000 123 -6891
150 951 512 -213
160 513 983 -123

Solution

  • I do not know why the previous version of this question was closed, because it was quite clear with sample data and desired results.

    With great pain in MS Access -- but it is possible. You need to enumerate the values and then combine them. I think this will work:

    select max(subcode), max(data), max(subcode_neg), max(data_neg)
    from (select subcode, data, null as subcode_neg, null as data_neg
                 (select count(*) from t as t2 where t2.subcode <= t.subcode and t2.data > 0
                 ) as seqnum
          from t
          where data > 0
          union all
          select null, null, subcode, data,
                 (select count(*) from t as t2 where t2.subcode <= t.subcode and t2.data < 0
                 ) as seqnum
          from t
          where data < 0
         ) as tt
    group by seqnum;