Skip to content
Advertisement

All columns from same table want to get them in tabular form in single query

I have this two query’s:

select CurBalName, CurBalAmount, CurBalDC from Tb_CurBal where curbaldc = 'C'
select CurBalName, CurBalAmount, CurBalDC from Tb_CurBal where curbaldc = 'D'

I would like to show them in the tabular form as shown on the image below…

Image1

Desired result:

DESIRED RESULT

Advertisement

Answer

One of the options:

Select case when curbaldc = 'D' then CurBalName
             else null 
        end CurBalName_D
        , case when curbaldc = 'D' then CurBalAmount
             else null 
        end CurBalAmount_D
        , case when curbaldc = 'D' then CurBalDC
             else null 
        end CurBalDC_D
        , case when curbaldc = 'C' then CurBalName
             else null 
        end CurBalName_C
        , case when curbaldc = 'C' then CurBalAmount
             else null 
        end CurBalAmount_C
        , case when curbaldc = 'C' then CurBalDC
             else null 
        end CurBalDC_C
from Tb_CurBal;

One more way:

select * from 
(select * from Tb_CurBal where curbaldc = 'D') A
full outer join
(select * from Tb_CurBal where curbaldc = 'C') B
on A.curbaldc = B.curbaldc

This will work on SQLServer:

select A.CurBalName, A.CurBalAmount, A.CurBalDC, 
       B.CurBalName, B.CurBalAmount, B.CurBalDC
from 
(select CurBalName, CurBalAmount, CurBalDC, row_number() over (order by CurBalName) rn
from Tb_CurBal where curbaldc = 'D') A
left join
(select CurBalName, CurBalAmount, CurBalDC, row_number() over (order by CurBalName) rn 
from Tb_CurBal where curbaldc = 'C') B
on A.rn = B.rn
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement