当我使用CASE
根据条件从多个表中获取列,并且由于使用了聚合函数而不得不在GROUP BY
中使用此名称时,如何保留原始列名?我需要它来创建正确的列名VIEW
。我使用PostgreSQL。
示例
我有三张table:
create table first
(
id bigserial primary key,
field varchar(255) not null
);
create table second
(
id bigserial primary key,
field varchar(255) not null,
first_id bigint constraint second_first_id references first
);
create table values
(
id bigserial primary key,
value numeric,
first_id bigint constraint value_first_id references first
);
一些输入数据:
insert into first (field) values ('aaa');
insert into first (field) values ('bbb');
insert into second (field, first_id) values ('ggg', 1);
insert into second (field, first_id) values ('hhh', 2);
insert into values (value, first_id) values (2, 1);
insert into values (value, first_id) values (4, 1);
insert into values (value, first_id) values (20, 2);
insert into values (value, first_id) values (40, 2);
和连接这些表并按以下方式分组的SQL:
select sum(v.value) as sum_value,
f.field,
s.field
from first f
left join second s on f.id = s.first_id
left join values v on f.id = v.first_id
group by f.field, s.field;
现在,我添加带有一些条件的CASE
语句(为了简单起见,true
),以从first
或second
表中获取字段field
:
select sum(v.value) as sum_value,
case
when true then
f.field
else
s.field
end as field
from first f
left join second s on f.id = s.first_id
left join values v on f.id = v.first_id
group by field;
存在错误:
ERROR: column reference "field" is ambiguous
我可以通过将as field
和group by field
更改为新名称来修复错误,例如field1
。
但我想保留原来的名字field
。创建视图时,这一点很重要:
create or replace view my_view as
select sum(v.value) as sum_value,
case
when true then
f.field
else
s.field
end as field1
from first f
left join second s on f.id = s.first_id
left join values v on f.id = v.first_id
group by field1;
select * from my_view;
视图返回名为field1
而不是field
的列。
我尝试通过group by my_view.field
限定视图中的名称as field
,但它也不起作用:
ERROR: missing FROM-clause entry for table "my_view"
我可以复制整个CASE
语句并将其粘贴到GROUP BY
中,但我认为这不是一个好的解决方案(特别是当CASE
非常长并且有很多列时):
create or replace view my_view as
select sum(v.value) as sum_value,
case
when false then
f.field
else
s.field
end as field
from first f
left join second s on f.id = s.first_id
left join values v on f.id = v.first_id
group by case
when false then
f.field
else
s.field
end;
1条答案
按热度按时间wz3gfoph1#
可以使用group by中列的序号。即: