如何重塑 PostgreSQL 中的特定行记录?
How to reshape specific row record in PostgreSQL?
我有 table 像这样存储在 PostgreSQL 中:
在我的例子中,我需要 select 特定行(例如 ID = 1),然后重塑 selected 行,所以输出将是这样的:
是否可以在单个 sql 查询中执行此逻辑?有人告诉我使用 "crosstab" 但我想不出解决它的方法..
我可能只是建议 union all
:
select 2010 as id_year, A_2010 as a, b_2010 as b from t
union all
select 2011 as id_year, A_2011 as a, b_2011 as b from t
union all
select 2012 as id_year, A_2012 as a, b_2012 as b from t
union all
select 2013 as id_year, A_2013 as a, b_2013 as b from t;
但是,横向连接可能更有效:
select v.*
from t, lateral
(values (2010, A_2010, B_2010), (2011, A_2011, B_2011),
(2012, A_2012, B_2012), (2013, A_2013, B_2013)
) v(id_year, A, B);
with t(id, A_2010,A_2011,A_2012,A_2013,B_2010,B_2011,B_2012,B_2013) as ( values
(1,'value 1','value 4','value 7','value 10','value 13','value 16','value 19','value 21')
)
select
unnest(array[2010,2011,2012,2013]) as "ID_YEAR",
unnest(array[A_2010,A_2011,A_2012,A_2013]) as "A",
unnest(array[B_2010,B_2011,B_2012,B_2013]) as "B"
from t
where id = 1
;
ID_YEAR | A | B
---------+----------+----------
2010 | value 1 | value 13
2011 | value 4 | value 16
2012 | value 7 | value 19
2013 | value 10 | value 21
我有 table 像这样存储在 PostgreSQL 中:
在我的例子中,我需要 select 特定行(例如 ID = 1),然后重塑 selected 行,所以输出将是这样的:
是否可以在单个 sql 查询中执行此逻辑?有人告诉我使用 "crosstab" 但我想不出解决它的方法..
我可能只是建议 union all
:
select 2010 as id_year, A_2010 as a, b_2010 as b from t
union all
select 2011 as id_year, A_2011 as a, b_2011 as b from t
union all
select 2012 as id_year, A_2012 as a, b_2012 as b from t
union all
select 2013 as id_year, A_2013 as a, b_2013 as b from t;
但是,横向连接可能更有效:
select v.*
from t, lateral
(values (2010, A_2010, B_2010), (2011, A_2011, B_2011),
(2012, A_2012, B_2012), (2013, A_2013, B_2013)
) v(id_year, A, B);
with t(id, A_2010,A_2011,A_2012,A_2013,B_2010,B_2011,B_2012,B_2013) as ( values
(1,'value 1','value 4','value 7','value 10','value 13','value 16','value 19','value 21')
)
select
unnest(array[2010,2011,2012,2013]) as "ID_YEAR",
unnest(array[A_2010,A_2011,A_2012,A_2013]) as "A",
unnest(array[B_2010,B_2011,B_2012,B_2013]) as "B"
from t
where id = 1
;
ID_YEAR | A | B
---------+----------+----------
2010 | value 1 | value 13
2011 | value 4 | value 16
2012 | value 7 | value 19
2013 | value 10 | value 21