sql oracle中不带聚合和常量表达式的透视表
我想制作一种透视表,但问题是透视的列必须等于今年和明年。我用一个例子来解释sql oracle中不带聚合和常量表达式的透视表,sql,oracle,pivot,Sql,Oracle,Pivot,我想制作一种透视表,但问题是透视的列必须等于今年和明年。我用一个例子来解释 with property(prop_name, prop_val, planned_year) as ( select 'BANKING', 'true' , '2018' from dual union all select 'IT' , 'false', '2019' from dual union all select 'TELECOM', 'false', '2
with
property(prop_name, prop_val, planned_year) as (
select 'BANKING', 'true' , '2018' from dual union all
select 'IT' , 'false', '2019' from dual union all
select 'TELECOM', 'false', '2019' from dual union all
select 'MEDIA' , 'false', '2020' from dual union all
select 'APPLE' , 'true' , '2018' from dual union all
select 'MANGO' , 'true' , '2019' from dual union all
select 'ORANGE' , 'false', '2019' from dual union all
select 'CARROT' , 'false', '2019' from dual union all
select 'IT' , 'true' , '2020' from dual
)
select *
from property
pivot (listagg(prop_val, ',') within group (order by null)
for planned_year in ('2019' this_year, '2020' next_year))
;
这就是我想要得到的结果,除了支点必须在今年的计划年(所以不是硬编码的2019年)。我试过这个:
with
property(prop_name, prop_val, planned_year) as (
select 'BANKING', 'true' , '2018' from dual union all
select 'IT' , 'false', '2019' from dual union all
select 'TELECOM', 'false', '2019' from dual union all
select 'MEDIA' , 'false', '2020' from dual union all
select 'APPLE' , 'true' , '2018' from dual union all
select 'MANGO' , 'true' , '2019' from dual union all
select 'ORANGE' , 'false', '2019' from dual union all
select 'CARROT' , 'false', '2019' from dual union all
select 'IT' , 'true' , '2020' from dual
)
select *
from property
pivot (listagg(prop_val, ',') within group (order by null)
for planned_year in (EXTRACT(YEAR FROM sysdate) this_year, EXTRACT(YEAR FROM sysdate)+1 next_year))
但是我得到了一个错误:
"non-constant expression is not allowed for pivot|unpivot values"
有人能帮我做这个把戏吗?我会在这里使用listag()
和case
:
with
property(prop_name, prop_val, planned_year) as (
select 'BANKING', 'true' , '2018' from dual union all
select 'IT' , 'false', '2019' from dual union all
select 'TELECOM', 'false', '2019' from dual union all
select 'MEDIA' , 'false', '2020' from dual union all
select 'APPLE' , 'true' , '2018' from dual union all
select 'MANGO' , 'true' , '2019' from dual union all
select 'ORANGE' , 'false', '2019' from dual union all
select 'CARROT' , 'false', '2019' from dual union all
select 'IT' , 'true' , '2020' from dual)
select prop_name,
listagg(case planned_year when to_char(sysdate, 'yyyy') then prop_val end, ',')
within group (order by null) this_year,
listagg(case planned_year when to_char(add_months(sysdate, 12), 'yyyy') then prop_val end, ',')
within group (order by null) next_year
from property
group by prop_name
order by prop_name
请显示您想要的结果。非工作查询不是表达意图的好方法。正如我提到的,我想要的结果是第一个查询的结果。但正如我也提到过的,我不想硬编码“2019”和“2020”,而是想选择今年和明年。