我如何从原始 table 创建视图和分组 - 以及平均值?

How could i create a view and group - and average - values from original table?

假设我有一个包含 3 列(工作日、价格 1 和价格 2)的 table,如下所示:

create table original_table 
(weekday VARCHAR(15), 
price1 number (6), 
price2 number(6));

insert into original_table values (‘tuesday’, 12, 23);
insert into original_table values (‘monday’, 23, 45);
insert into original_table values (‘friday’, 45, 21);
insert into original_table values (‘friday’, 231, 34);
insert into original_table values (‘monday’, 35, 53);
insert into original_table values (‘tuesday’, 213, 9);

我想根据这个原始 table 创建一个视图,按特定列(工作日) 对价格(Price1 和 Price2)进行分组和平均。留下这样的东西:

我用来创建视图和平均价格的代码。与我的预期输出相差甚远,但它要开始了。

create view view_from_original_table as
weekday, avg_price1, avg_price2
select weekday, avg(price1), avg(price2)
from original_table
group by weekday;

我认为使用 pivot 我可以达到这个结果,但我很难理解它。

你可以用 case 语句来做到这一点

这里是fiddlehttps://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=e9f1bec3e9da3319a31a92eb9aa11b11

with t as (select weekday, avg(price1) p1 , avg(price2) p2
from original_table
group by weekday)
select  t.weekday, 
case t.weekday when 'monday' then p1 end as Monday_avg1,
case t.weekday when 'monday' then p2 end as Monday_avg2,
case t.weekday when 'tuesday' then p1 end as Tuesday_avg1,
case t.weekday when 'tuesday' then p2 end as Tuesday_avg2,
case t.weekday when 'friday' then p1 end as Friday_avg1,
case t.weekday when 'friday' then p2 end as Friday_avg2
from t
order by case weekday when 'monday' then 1 when 'tuesday' then 2 else 3 end