0

次の行を含むテーブルがあります。

product_id | order_date
A          | 12/04/12
A          | 01/11/13
A          | 01/21/13
A          | 03/05/13
B          | 02/14/13
B          | 03/09/13

今必要なのは、毎月の概要、初めて購入した製品の数(=前月に購入していない)、既存の製品の数(=前月に購入した製品)、および購入した製品の数です。特定の月内に購入されていません。上記のサンプルを入力として使用すると、データに含まれる期間に関係なく、スクリプトは次の結果を提供する必要があります。

month   | new | existing | nopurchase
12/2012 | 1   | 0        | 0
01/2013 | 0   | 1        | 0
02/2013 | 1   | 0        | 1
03/2013 | 1   | 1        | 0

これをどのように解決できるかについての最初のヒントを得て、続行できるようにするとよいでしょう。

ありがとう!

4

1 に答える 1

0

SQLフィドル

with t as (
    select product_id pid, date_trunc('month', order_date)::date od
    from t
    group by 1, 2
)
select od,
    sum(is_new::integer) "new",
    sum(is_existing::integer) existing,
    sum(not_purchased::integer) nopurchase
from (
    select od,
        lag(t_pid) over(partition by s_pid order by od) is null and t_pid is not null is_new,
        lag(t_pid) over(partition by s_pid order by od) is not null and t_pid is not null is_existing,
        lag(t_pid) over(partition by s_pid order by od) is not null and t_pid is null not_purchased
    from (
        select t.pid t_pid, s.pid s_pid, s.od
        from
            t
            right join
            (
                select pid, s.od
                from
                    t
                    cross join
                    (
                        select date_trunc('month', d)::date od
                        from
                        generate_series(
                            (select min(od) from t),
                            (select max(od) from t),
                            '1 month'
                        ) s(d)
                    ) s 
                group by pid, s.od
            ) s on t.od = s.od and t.pid = s.pid
    ) s
) s
group by 1
order by 1
于 2013-03-13T17:33:12.193 に答える