微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql使用经验

临时表

此处需要存储一次select的结果集用来进行第二次连接。

with temp1 as (select * from t_energy_type where company_id = 991897881281560576 and del_status = 1),
     temp2 as (select b.value, a.energy_type_id
               from t_energy_type a
                        left join t_unit_consumption b on b.energy_type_id = a.energy_type_id and b.del_status = 1
                        left join t_system_group c on c.group_id = b.group_id and c.del_status = 1
               where a.del_status = 1
                 and a.company_id = 991897881281560576
                 and b.type = 'M' --时间类型
                 and c.type = 1
                 and to_date(to_char(record_date, 'yyyy-mm'), 'yyyy-mm') =
                     to_date('2021-02-28', 'yyyy-mm'))
select t1.name, t1.english_name, t2.value, t1.energy_type_id
from temp1 t1
         left join temp2 t2 on t2.energy_type_id = t1.energy_type_id;

可以用 with temp1 as (第一次查询),temp as (第二次查询) select * from temp1 left join temp 2 on **** = ***;
的语句把两次结果进行再次关联。

特定业务,比如计算环比 需要用两个同样语句的不同时间条件进行比较计算的情景,可以用临时表存储,再进行查询结果。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐