2017-04-18 12 views
2

によってソート私はunionを使用して、3つのテーブルからいくつかのデータを選択し、その後、私は、日付とタイムスタンプによってそれらをソートしたいと思います(降順):オラクル:日付とタイムスタンプ

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 

どのように期待された並べ替えの結果を得るためのアイデア?

ありがとうございます。

+1

'sort by'?オラクルでは? –

+0

なぜORDER BY a.dateを使用しないのですか –

+0

私は "order by"に更新しました。並べ替えは打ち間違いだった –

答えて

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); 
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; 
0

まず、UNIONクエリのためのあなたの構文が間違っています。エイリアスは最初のSELECTでのみ作成できます。 UNIONバージョンは、すべて同じデータ型のフィールドを選択するだけです。

第2に、サブクエリでユニオンを実行すると、そのサブクエリから直接選択することができます。

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 
関連する問題