简体   繁体   English

如何将表转换为数据透视表(或转置)表?

[英]How can I convert a table to pivot(or transpose) table?

I have a table like this: table1:我有一个这样的表:table1:

month       pool_name     apy
------------------------------
04-2021         a          1
04-2021         c          2
04-2021         d          1
04-2021         f          3
04-2021         g          5
04-2021         h          6
05-2021         a          2 
05-2021         b          3
05-2021         c          2
05-2021         e          7
05-2021         f          5
05-2021         h          6
05-2021         i          4
.
.
.

how can I transpose or pivot (actully I don't know about that) the table1 to table2:我如何将 table1 或 pivot(实际上我不知道)转置到 table2:

month     a    b   c    d    e    f    g    h   i
----------------------------------------------------
04-2021   1    0   2    1    0    3    5    6   0
05-2021   2    3   2    0    7    5    0    6   4

I use this code but I have an error.我使用此代码,但出现错误。

select month,pool_name,apy from table1
    pivot (sum(apy) for pool_name in (select distinct(pool_name) from table1))

I have to write this code in snowflake (classic web interface).我必须在雪花(经典的 web 界面)中编写这段代码。 Thank you in advance.先感谢您。

For Dynamic pivot you need to use a procedure or script.对于 Dynamic pivot,您需要使用过程或脚本。 Dynamic pivot on table (column - "pool_name"):表上的动态 pivot(列 - “pool_name”):

Main Query主查询

EXECUTE IMMEDIATE $$
declare 
res resultset;
itm_name varchar2(2000):=null;
col_list varchar2(2000):=null;
c1 cursor for select distinct pool_name from tab_pool order by pool_name desc;
BEGIN
  for rec in c1 do
  itm_name := NVL2(itm_name,concat(',',itm_name),'');
  itm_name := '\''||rec.pool_name||'\''||itm_name;
  col_list := NVL2(col_list,concat(',',col_list),'');
  col_list := 'NVL("\''||rec.pool_name||'\'",0) as '||rec.pool_name||col_list;
  end for;
  res := (execute immediate 'select month,'||col_list||' from tab_pool pivot(min(apy) for pool_name in ('||itm_name||'))');
  return table(res);
 return col_list;
END;
$$
;

Output received - Output 收到 -

+---------+---+---+---+---+---+---+---+---+---+
| MONTH   | A | B | C | D | E | F | G | H | I |
|---------+---+---+---+---+---+---+---+---+---|
| 04-2021 | 1 | 0 | 2 | 1 | 0 | 3 | 5 | 6 | 0 |
| 05-2021 | 2 | 3 | 2 | 0 | 7 | 5 | 0 | 6 | 4 |
+---------+---+---+---+---+---+---+---+---+---+

Data-set used -使用的数据集 -

create temporary table tab_pool 
(month varchar2(20), 
pool_name varchar2(5), 
apy number);

insert into tab_pool values
('04-2021','a',1),
('04-2021','c',2),
('04-2021','d',1),
('04-2021','f',3),
('04-2021','g',5),
('04-2021','h',6),
('05-2021','a',2), 
('05-2021','b',3),
('05-2021','c',2),
('05-2021','e',7),
('05-2021','f',5),
('05-2021','h',6),
('05-2021','i',4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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