CREATE TABLE gir_outstanding_aged
AS (
SELECT    group_code::text                          AS group_code,
          sku::text                                 AS sku,
          stktype_code::varchar(2)                  AS stktype_code,
          brn_code::text                            AS brn_code,
          SUM(overdue)::int4                        AS overdue,
          SUM(current)::int4                        AS current,
          SUM(future)::int4                         AS future
FROM (
SELECT    group_code,
          sku,
          stktype_code,
          brn_code,
          CASE WHEN to_date <= max_fpp_ms() THEN
             SUM(out_qty)
          ELSE  0
          END                                     AS overdue,
          CASE WHEN to_date > max_fpp_ms()
          AND to_date <= max_fpp_me() THEN
             SUM(out_qty)
          ELSE 0
          END                                     AS current,
          CASE WHEN to_date > max_fpp_me() THEN
             SUM(out_qty)
          ELSE 0
          END                                     AS future
FROM gir_outstanding
GROUP BY  group_code,
          sku,
          stktype_code,
          brn_code,
          to_date
) AS sub
GROUP BY  group_code,
          sku,
          stktype_code,
          brn_code
);
