2016-02-07 63 views
0

銷售數據包含可以包含任何字符的動態產品名稱。基於樣本創建從 Crosstab with a large or undefined number of categories如何保留動態數據透視表上的列名

動態透視表翻譯()被用於去除壞字符。

結果數據透視表列名已損壞:缺少字符和空格被刪除。 如何使用與源數據中相同的列名返回數據? 我試圖用

quote_ident(productname) as tootjakood, 

代替

'C'||upper(Translate(productname,'Ø. &/+-,%','O')) as tootjakood, 

錯誤,將返回錯誤:列 「Ø,12.3 /3毫米」 不存在

測試用例:

create temp table sales (saledate date, productname char(20), quantity int); 
insert into sales values ('2016-1-1', 'Ø 12.3/3mm', 2); 
insert into sales values ('2016-1-1', '+-3,4%/3mm', 52); 
insert into sales values ('2016-1-3', '/3,2m-', 246); 

do $do$ 


declare 
voter_list text; 
begin 

create temp table myyk on commit drop as 
select saledate as kuupaev, 
    'C'||upper(Translate(productname,'Ø. &/+-,%','O')) as tootjakood, 
    sum(quantity)::int as kogus 
from sales 
group by 1,2 
; 

drop table if exists pivot; 

voter_list := (
    select string_agg(distinct tootjakood, ' ' order by tootjakood) from myyk 
    ); 

execute(format(' 
    create table pivot (
kuupaev date, 
     %1$s 
    )', (replace(voter_list, ' ', ' integer, ') || ' integer') 
)); 

execute (format($f$ 

    insert into pivot 
     select 
      kuupaev, 
      %2$s 
     from crosstab($ct$ 
      select 
       kuupaev,tootjakood,kogus 
      from myyk 
      order by 1 
      $ct$,$ct$ 
      select distinct tootjakood 
      from myyk 
      order by 1 
      $ct$ 
     ) as (
      kuupaev date, 
      %4$s 
     );$f$, 

     replace(voter_list, ' ', ' + '), 
     replace(voter_list, ' ', ', '), 
     '', 
     replace(voter_list, ' ', ' integer, ') || ' integer' -- 4. 
    )); 
end; $do$; 

select * from pivot; 

使用Postgres 9.1。

回答

1

您應該使用雙引號。因爲您正在使用空格來標識列分隔符,所以應該從列名稱中刪除空格(或更改分隔符標識的方式)。

隨着

... 
select saledate as kuupaev, 
    format ('"%s"', replace (upper(productname), ' ', '')) as tootjakood, 
    sum(quantity)::int as kogus 
from sales 
... 

你會得到:

kuupaev | /3,2M- | +-3,4%/3MM | O12.3/3MM 
------------+--------+------------+----------- 
2016-01-01 |  |   52 |   2 
2016-01-03 | 246 |   |   
(2 rows) 
+0

非常感謝你。有相關的問題在http://stackoverflow.com/questions/35266931/returning-empty-data-from-dynamic-pivot-is-there-is-no-data – Andrus