我使用union
从三个表中选择一些数据然后我想按日期和时间戳(降序)对它们进行排序:
select reportname as name, convert_to_char(a.date) AS created,
....
from table1
UNION
select reportname as name, convert_to_char(a.date) AS created,
....
from table2
UNION
select reportname as name, convert_to_char(a.date) AS created,
....
from table3
order by created desc;
convert_to_char实现如下:
create or replace function convert_to_char(myDate date)
RETURN varchar IS
BEGIN
return TO_CHAR(cast (myDate as timestamp) at local, 'YYYY-MM-DD HH24:MI:SS TZH:TZM');
END;
我得到的排序数据的结果如下:
created
------------------
2017-04-12 16:07:07 +02:00
2017-04-13 09:00:01 +02:00
2017-04-13 09:00:40 +02:00
2017-04-12 16:06:17 +02:00
2017-04-12 16:08:37 +02:00
2017-04-12 16:07:31 +02:00
2017-04-13 09:00:25 +02:00
2017-04-13 09:00:25 +02:00
2017-04-12 16:09:07 +02:00
2017-04-12 16:08:20 +02:00
2017-04-12 16:08:06 +02:00
2017-04-12 16:06:48 +02:00
但我希望以下排序结果:
created
------------------
2017-04-13 09:00:40 +02:00
2017-04-13 09:00:25 +02:00
2017-04-13 09:00:25 +02:00
2017-04-13 09:00:01 +02:00
2017-04-12 16:09:07 +02:00
2017-04-12 16:08:37 +02:00
2017-04-12 16:08:20 +02:00
2017-04-12 16:08:06 +02:00
2017-04-12 16:07:31 +02:00
2017-04-12 16:07:07 +02:00
2017-04-12 16:06:48 +02:00
2017-04-12 16:06:17 +02:00
知道如何获得预期的排序结果吗?
提前谢谢。
答案 0 :(得分:3)
您可以先对它们进行排序,然后选择
select name, created
from
(select reportname as name, convert_to_char(a.date) AS created, a.date,
....
from table1
UNION
select reportname as name, convert_to_char(a.date) AS created, a.date
....
from table2
UNION
select reportname as name, convert_to_char(a.date) AS created, a.date
....
from table3
order by a.date desc);
答案 1 :(得分:3)
尝试:
select name, convert_to_char(created) from (
select reportname as name, date AS created,
....
from table1
UNION
select reportname as name, date AS created,
....
from table2
UNION
select reportname as name, date AS created,
....
from table3
) t
order by created desc;
答案 2 :(得分:0)
首先,您对UNION查询的语法是错误的。您只能在第一个SELECT上创建别名。 UNION版本只需选择具有相同数据类型的字段。
其次,通过在子查询中执行联合,您可以直接从中进行选择,它将按顺序排列。
WITH TotalTable AS (
select reportname as name, convert_to_char(a.date) AS created,
....
from table1
UNION
select reportname, convert_to_char(a.date),
....
from table2
UNION
select reportname, convert_to_char(a.date),
....
from table3)
SELECT reportname, created FROM TotalTable
ORDER BY created DESC