CROSSTAB PostgreSQL - Oracle中PIVOT的替代方案

时间:2017-12-22 19:48:16

标签: postgresql crosstab postgresql-9.4

我正在将Oracle数据库的查询迁移到PostgreSQL交叉表。

create table(cntry numeric,week numeric,year numeric,days text,day text);
insert into x_c values(1,15,2015,'DAY1','MON');
...
insert into x_c values(1,15,2015,'DAY7','SUN');
insert into x_c values(2,15,2015,'DAY1','MON');
...
                values(4,15,2015,'DAY7','SUN');

我在桌子上有4个星期,有28行。我的Oracle查询如下所示:

SELECT * FROM(select * from x_c)
PIVOT (MIN(DAY) FOR (DAYS) IN
   ('DAY1' AS DAY1 ,'DAY2' DAY2,'DAY3' DAY3,'DAY4' DAY4,'DAY5' DAY5,'DAY6' DAY6,'DAY7' DAY7 ));

结果:

cntry|week|year|day1|day2|day3|day4|day4|day6|day7|
---------------------------------------------------
   1 | 15 |2015| MON| TUE| WED| THU| FRI| SAT| SUN|
...
   4 | 18 |2015| MON| ...

现在我写了一个像这样的Postgres交叉表查询:

select *
from crosstab('select cntry,week,year,days,min(day) as day
               from x_c
               group by cntry,week,year,days'
             ,'select distinct days from x_c order by 1'
             ) as (cntry numeric,week numeric,year numeric
                  ,day1 text,day2 text,day3 text,day4 text, day5 text,day6 text,day7 text);

我只输出一行作为输出:

  1|17|2015|MON|TUE| ...   -- only this row is coming

我在哪里做错了?

2 个答案:

答案 0 :(得分:1)

原始查询中缺少

ORDER BY。手册:

  

实际上,SQL查询应始终指定ORDER BY 1,2以确保输入行的顺序正确,即具有相同row_name的值汇集在一起​​并在行内正确排序。

更重要的是(而且更棘手),crosstab()完全需要 一个 row_name 列。这个密切相关的答案的详细解释:

solution you found是在一个数组中嵌套多个列,然后再次取消。这是不必要的昂贵,容易出错和有限(仅适用于具有相同数据类型的列,或者您需要强制转换并可能丢失正确的排序顺序)。

相反,使用rank()dense_rank()(在我的示例中为rnk)生成代理 row_name 列:

SELECT cntry, week, year, day1, day2, day3, day4, day5, day6, day7
FROM   crosstab (
  'SELECT dense_rank() OVER (ORDER BY cntry, week, year)::int AS rnk
        , cntry, week, year, days, day
   FROM   x_c
   ORDER  BY rnk, days'
 , $$SELECT unnest('{DAY1,DAY2,DAY3,DAY4,DAY5,DAY6,DAY7}'::text[])$$
   ) AS ct (rnk int, cntry int, week int, year int
          , day1 text, day2 text, day3 text, day4 text, day5 text, day6 text, day7 text)
ORDER  BY rnk;

我将数据类型integer用于列cntryweekyear,因为这似乎是(更便宜)合适的类型。您也可以像使用数字一样使用数字。

此处交叉表查询的基础知识:

答案 1 :(得分:0)

我从http://www.postgresonline.com/journal/categories/24-tablefunc

得到了这个结果
  select year_wk_cntry.t[1],year_wk_cntry.t[2],year_wk_cntry.t[3],day1,day2,day3,day4,day5,day6,day7
   from crosstab('select  ARRAY[country :: numeric,week,year] as t,days,min(day) as day
                            from x_c group by country,week,year,days order by 1,2
                            ','select distinct days from x_c order by 1')
                            as year_wk_cntry (t numeric[],day1 text,day2 text,day3 text,
         day4 text, day5 text,day6 text,day7 text);

谢谢!