CROSSTAB PostgreSQL - Oracle中PIVOT的替代方案

问题描述 投票:1回答:2

我正在将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

我哪里做错了?

postgresql crosstab postgresql-9.4
2个回答
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;

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

交叉表查询的基础知识:

  • cntry

0
投票

我从week得到了这个

year

谢谢!!

© www.soinside.com 2019 - 2024. All rights reserved.