sql - PostgreSQL - 如何循环参数以合并同一张表的不同查询
问题描述
我需要计算给定年份仍然发生的事件数量,前提是这些事件在给定年份之前开始并在之后结束。所以,我现在使用的查询只是一堆未参数化的查询,我想用一个参数循环写出来:
select
count("starting_date" ) as "number_of_events" ,'2020' "year"
from public.table_of_events
where "starting_date" < '2020-01-01' and ("closing_date" > '2020-12-31')
union all
select
count("starting_date" ) as "number_of_events" ,'2019' "year"
from public.table_of_events
where "starting_date" < '2019-01-01' and ("closing_date" > '2019-12-31')
union all
select
count("starting_date" ) as "number_of_events" ,'2018' "year"
from public.table_of_events
where "starting_date" < '2018-01-01' and ("closing_date" > '2018-12-31')
...
...
...
and so on for N years
所以,我有一张表,必须根据一个参数进行过滤,该参数既是select
语句的一部分又是where
子句的一部分
“原子”查询的一般方面是
select
count("starting_date" ) as "number_of_events" , **PARAMETER** "year"
from public.table_of_events
where "starting_date" < **PARAMETER** and ("closing_date" > **PARAMETER** )
union all
谁能帮我把它放在一个更正式的循环中?
非常感谢,我希望我足够清楚。
解决方案
您似乎想要跨越整年的事件。也许一个简单的方法是生成年份,然后使用join
和聚合:
select gs.yyyy, count(e.starting_date)
from public.table_of_events e left join
generate_series('2015-01-01'::date,
'2021-01-01'::date,
interval '1 year'
) as gs(yyyy)
on e.starting_date < gs.yyyy and
e.closing_date >= gs.yyyy + interval '1 year'
group by gs.yyyy;
推荐阅读
- java - Android Studio:任务“:app:transformClassesWithDexBuilderForDebug”执行失败
- javascript - 如何以编程方式显示页面包中的所有图像
- r - 将列表列表转换为 R 中的数据框。我需要列表列表的名称作为列
- idl-programming-language - 如何在 IDL 程序中找到算术错误的来源?
- sql - 如何进行全外连接。没有得到预期的结果
- ruby-on-rails - Ruby on Rails - 提交嵌套资源表单不保存,产生“过滤器链停止为:require_no_authentication 呈现或重定向”
- webpack - 使用 Webpack 4 编译 Stylus 而不将其导入 JS 文件?
- scala - Spark:即使生产者没有明确编码,Kafka 消费者也会将数据作为 base64 编码的字符串获取
- c# - 警告 NETSDK1071 对“Microsoft.AspNetCore.App”的 PackageReference 指定了“2.1.6”版本
- php - 使用 Laravel Forge 的负载均衡器得到 404 CSS