我有大约五个查询产生相同类型的输出,唯一的区别是它们从单独的表中获取数据,如每小时表,每日表,每周表。
现在我想根据用户的输入编写一个查询,从五个表中的一个表生成输出。 E.g。
IF THE USER PROVIDED TIMERANGE IS GREATER THAN 1 AND LESS THAN 24 HRS
THEN EXTRACT FROM HOURLY TABLE--i.e. execute 1st query
IF THE USER PROVIDED TIMERANGE IS GREATER THAN 24 AND LESS THAN 7 DAYS
THEN EXTRACT FROM DAILY TABLE-- i.e. execute 2nd query
.....等等
注意:所有五个查询都返回相同类型的输出。也就是说,select子句的投影对于所有查询都是相同的。
这可以通过单个SQL语句(可能使用union)完成,还是需要为此编写PL / SQL?
答案 0 :(得分:2)
您可以使用UNION ALL运算符执行此操作:
select * from hourly_table
where (&&user_end_date - &&user_start_day) < 1
union all
select * from weekly_table
where (&&user_end_date - &&user_start_day) between 1 and 7
union all
select * from monthly_table
where &&user_end_date <= add_months(&&user_start_day, 1)
union all
select * from yearly_table
where &&user_end_date <= add_months(&&user_start_day, 12)
union all
select * from whatever_table
where &&user_end_date > add_months(&&user_start_day, 12)
我已将SQL * Plus语法用于替换变量;您可能需要更改此选项以适合您用于运行查询的任何客户端。
答案 1 :(得分:0)
CASE .. WHEN可能有帮助
select
CASE ConditionVar
WHEN Val1 THEN Query1
WHEN Val2 THeN Query2
ELSE QUERY3
END as myresult
from my_tables (dual in case no need of table);
案件的详细解释 http://www.techonthenet.com/oracle/functions/case.php
替代语法,这在您的情况下可能更有用
select
CASE
WHEN condition1 THEN Query1
WHEN condition2 THeN Query2
ELSE QUERY3
END as myresult
from my_tables (dual in case no need of table);