我想从我的数据中的一个列动态创建列。在我的情况下,我需要通过run_date对数据进行分组,并将每个marketplace_code作为列名。
所以基本上我需要转换这些数据:
run_date, marketplace_code, count
06-APR-16, US, 1125197
06-APR-16, MX, 26873
06-APR-16, IT, 5197
06-APR-16, UK, 23873
05-APR-16, US, 486889
05-APR-16, MX, 486819
05-APR-16, IT, 536889
05-APR-16, UK, 986819
看起来像这样:
run_date, US, MX, IT, UK
06-APR-16, 1125197, 26873, 5197, 23873
05-APR-16, 486889, 486819, 536889, 986819
我尝试使用枢轴,但我不知道如何解决这个问题。此外,我们需要考虑marketplace_code的数量不固定,可能会增加。提前谢谢。
答案 0 :(得分:0)
SQL for static pivot values :
SELECT run_date,
MAX( CASE marketplace_code WHEN 'US' THEN "count" END ) AS US,
MAX( CASE marketplace_code WHEN 'MX' THEN "count" END ) AS MX,
MAX( CASE marketplace_code WHEN 'IT' THEN "count" END ) AS IT,
MAX( CASE marketplace_code WHEN 'UK' THEN "count" END ) AS UK
FROM you_table
GROUP BY run_date;
动态透视值的PL / SQL :
VARIABLE cur REFCURSOR;
DECLARE
TYPE string_table IS TABLE OF VARCHAR2(4000);
t_codes string_table;
p_sql CLOB;
BEGIN
SELECT DISTINCT marketplace_code
BULK COLLECT INTO t_services, t_counts
FROM your_table;
p_sql := EMPTY_CLOB() || 'SELECT run_date';
FOR i IN 2 .. t_codes.COUNT LOOP
p_sql := p_sql || ', MAX( CASE marketplace_code WHEN '''
|| t_codes(i)
|| ''' THEN "count" END ) AS "'
|| t_codes(i)
|| '"';
END LOOP;
p_sql := p_sql || ' FROM your_table GROUP BY run_date';
OPEN :cur FOR p_sql;
END;
/
PRINT cur;