交叉表问题

时间:2019-10-11 06:35:54

标签: sql postgresql group-by crosstab

我需要在表上使用交叉表功能。 表格数据如下:

program_id  | month  | orig_file_name
1            Jun-2019     x1
1            Jul-2019     x2
1            Aug-2019     x3
9            Jun-2019     x4
9            Aug-2019     x5
9            Jul-2019     x6
6            Jun-2019     x7
6            Sep-2019     x8
10           Sep-2019     x9
15           Jun-2019     x10
15           Aug-2019     x11
8            Jun-2019     x12
8            Jul-2019     x13
8            Aug-2019     x14
8            Sep-2019     x15

我需要这样的结果:

pgm_id | Jun-2019 | Jul-2019 | Aug-2019 | Sep-2019
1           x1        x2         x3 
9           x4        x6         x5 
6           x7                               x8
10                                           x9
15          x10                  x11    
8           x12       x13        x14        x15

我使用了以下查询:

SELECT *
    FROM crosstab(
      $$SELECT program_id,month,orig_file_name
       from tbl
      WHERE to_date(month,'Mon-YYYY') >= date_trunc('month', current_date - interval '4' month) 
      and to_date(month,'Mon-YYYY') < date_trunc('month', current_date) -- previous 4 month data   
 and record_status='A'
    and month = ANY('{Sep-2019,Aug-2019,Jul-2019,Jun-2019}')
       order by 1$$)
    AS t(row_1 int, "Sep-2019" text, "Aug-2019" text, "Jul-2019" text,"Jun-2019" text);

但是我没有得到预期的结果。

0 个答案:

没有答案
相关问题