Oracle

透視堆疊圖表的數據(為每個不同的值分組和創建新列)?

  • October 11, 2012

我有一些看起來像這樣的東西(這裡是 SQL Fiddle):

Date        Location    Value
1/1/2012    Baltimore   36
1/1/2012    Houston     36
1/1/2012    Chicago     55
2/1/2012    Baltimore   49
2/1/2012    Houston     58
2/1/2012    Chicago     51
3/1/2012    Baltimore   11
3/1/2012    Houston     13
3/1/2012    Chicago     18

但是,我希望它看起來像這樣:

Date        Baltimore   Houston     Chicago
1/1/2012    36          36          55
2/1/2012    49          58          51
3/1/2012    11          13          18

如何按 分組Date並為每個不同的列創建新列Location?我不知道完整的可能Locations 集。我正在使用 Oracle 11g 第 2 版。

如果列已知,另一種方法是使用聚合和CASE語句:

SELECT d,
 sum(case when loc = 'Baltimore' then v else 0 end) as Baltimore,
 sum(case when loc = 'Houston' then v else 0 end) as Houston,
 sum(case when loc = 'Chicago' then v else 0 end) as Chicago
FROM test
group by d
order by d;

請參閱帶有展示的 SQL Fiddle

如果要動態執行此操作,則可以創建一個過程來生成 SQL 語句:

CREATE OR REPLACE procedure dynamic_pivot(p_cursor in out sys_refcursor)
as
   sql_query varchar2(1000) := 'select d ';

   begin
       for x in (select distinct loc from test order by 1)
       loop
           sql_query := sql_query ||
               ' , sum(case when loc = '''||x.loc||''' then v end) as '||x.loc;

               dbms_output.put_line(sql_query);
       end loop;

       sql_query := sql_query || ' from test group by d order by 1';

       open p_cursor for sql_query;
   end;
/

然後呼叫它:

variable x refcursor
exec dynamic_pivot(:x)
print x

結果是:

D                                BALTIMORE    CHICAGO    HOUSTON
------------------------------- ---------- ---------- ----------
01-JAN-12 12.00.00.000000 AM            36         55         36
01-FEB-12 12.00.00.000000 AM            49         51         58
01-MAR-12 12.00.00.000000 AM            11         18         13

引用自:https://dba.stackexchange.com/questions/25280