首页 > 解决方案 > SQL 查询:是否可以在单个查询中投影四个结果?

问题描述

目前,我正在执行四个查询来预测基于过去 24 小时、上周、上个月和上个月的结果。是否可以在单个查询中投影四个结果?

标签: sqloracleperformance

解决方案


如果您需要与当前日期相比的最后一周、上个月、上一年,那么您可以使用 oracle 中的条件聚合来完成,如下所示:

Select sum(case when trunc(date_col) = trunc(sysdate-1) then 1 end) as last_one_day,
sum(case when trunc(date_col) between trunc(sysdate-7) and trunc(sysdate-1) then 1 end) as last_one_week,
sum(case when trunc(date_col) between trunc(add_months(sysdate,-1)) and trunc(sysdate-1) then 1 end) as last_one_month,
sum(case when trunc(date_col) between trunc(add_months(sysdate,-12)) and trunc(sysdate-1) then 1 end) as last_one_year
From your_table
Where type = ...

干杯!!


推荐阅读