これについていくつか質問がありましたが、関連する結果が見つかりませんでした。2 列の結果が得られるクエリがあります。
Day Tot_dLS
01-Sep-12 10000
02-Sep-12 9920
Date を次のように転置したい:
01-Sep-12 02-Sep-12
10000 9920
これは可能ですか?
このコード:
create table your_table(day date, tot_dls number(5));
insert into your_table values ('01-SEP-2012',10000);
insert into your_table values ('02-SEP-2012',9920);
insert into your_table values ('03-SEP-2012',12020);
insert into your_table values ('04-SEP-2012',11030);
column dummy noprint
column "Header" format a7
column "Data" format a60
set hea off
SELECT 0 DUMMY
,'Day' "Header"
,LISTAGG(' ' || TO_CHAR(Day,'DD-MON-YYYY')) WITHIN GROUP (ORDER BY Day) "Data"
FROM your_table
UNION
SELECT 1
,'Tot_dls'
,LISTAGG(LPAD(TOT_DLS,13-LENGTH(TO_CHAR(TOT_DLS,'FM')),' ')) WITHIN GROUP (Order by Day)
FROM your_table
ORDER by 1;
Oracle 11g(11.2.0)データベースでSQL*Plusを使用してこの出力を生成します。
Day 01-SEP-2012 02-SEP-2012 03-SEP-2012 04-SEP-2012
Tot_dls 10000 9920 12020 11030
固定数の列を返すことができ、一般的な列名を使用できるため、標準のピボットクエリを実行できます
SELECT max( case when rn = 1 then tot_dls else null end ) col_1,
max( case when rn = 2 then tot_dls else null end ) col_2,
max( case when rn = 3 then tot_dls else null end ) col_3,
<<25 more>>
max( case when rn = 29 then tot_dls else null end ) col_29,
max( case when rn = 30 then tot_dls else null end ) col_30
FROM (SELECT day,
tot_dls,
rank() over (order by day) rn
FROM your_table
WHERE day between date '2012-09-01'
and date '2012-09-02' -- Use whatever criteria you want here
)
同じ列に2つの異なるデータ型を含める必要があるため、SQLクエリではそうではありません。いくつかのトリック (すべてを文字列にキャストする) でやり遂げることができますが、そのようなことは、クエリから行うよりも、プレゼンテーション アプリケーションまたはレポート自体で行う方がはるかに優れています。
CASE
これを実行するには、ステートメントと集計を使用できます。次のようなものを使用できます。
select max(case when day = '01-Sep-12' then Tot_dLS end) "01-Sep-12",
max(case when day = '02-Sep-12' then Tot_dLS end) "02-Sep-12",
........ add more columns here
from yourtable
次に、これを拡張して列を追加します。