简体   繁体   中英

SQL transpose data into columns

I have the data as below.

ACCOUNT_KEY     monthend    BALANCE_EFC
---------------------------------------
AA391F177B83C0  2019-01-31  22.520
AA391F177B83C0  2019-02-28  22.520
AA391F177B83C0  2019-03-31  22.520
AA391F177B83C0  2019-04-30  22.520
AA391F177B83C0  2019-05-31  22.520
AA391F177B83C0  2019-06-30  22.520
AA391F177B83C0  2019-07-31  22.520
AA391F177B83C0  2019-08-31  22.520
AA391F177B83C0  2019-09-30  22.520
AA391F177B83C0  2019-10-31  22.520
AA391F177B83C0  2019-11-30  22.520
AA391F177B83C0  2019-12-31  22.520
AA391F177B83C0  2020-01-31  22.520

I would need some help in SQL to get this into

Accountkey       2019-01-31  2019-02-28  2019-03-31
---------------------------------------------------
AA391F177B83C0    22.520     22.520      22.520

You can use conditional aggregation:

select Accountkey,
       max(case when monthend = '2019-01-31' then BALANCE_EFC end) as "2019-01-31",
       max(case when monthend = '2019-02-28' then BALANCE_EFC end) as "2019-02-28",
       max(case when monthend = '2019-03-31' then BALANCE_EFC end) as "2019-03-31"
from t
group by Accountkey

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM