在PostgreSQL中创建一个Void函数

时间:2016-10-10 04:41:26

标签: postgresql

我在Postgresql中遇到这个创建函数代码的错误。错误说它发生在DELETE的2号线附近,但是如果我删除那行就发生在WITH,所以我认为这是我的Creat Function格式的问题

create or replace function retention_data(shopId integer) returns void as $$
    delete from retention where shop_id = shopId;

    WITH ret_grid_step1 as (
        select * from (

        SELECT 
            order_id as order_name,
            cust_name as cust_name,
            email as email,
            date(order_date) as created_at,
            count(*) as num_items_in_order,
            sum(total_price) as sales ,
            rank() over (partition BY order_id ORDER BY cust_name ASC) as rnk_shipping_name,
            rank() over (partition BY order_id ORDER BY email ASC) as rnk_email
        FROM orders 
         WHERE shop_id = shopId
         and order_date is not null and order_date > now()::date - 365 and order_date < now()::date + 1
         group by 1,2,3,4
        ) x
        where rnk_shipping_name = 1 and rnk_email = 1
    )
        insert into retention(shop_id, cust_name, email, last_purchase_dt, total_sales, num_orders, days_since_last_order)
            select
            shopId as shop_id,
            coalesce(b.cust_name,'null') as cust_name,
            a.email,
            a.last_purchase_dt,
            total_sales,
            num_orders,
            current_date - last_purchase_dt as days_since_last_order
        from (
            select
                email,
                max(created_at) as last_purchase_dt,
                count(*) as num_orders,
                sum(sales) as total_sales
            from ret_grid_step1
            group by 1
        ) as a
        left join (
            select
                email,
                cust_name,
                rank() over (partition BY email ORDER BY created_at DESC) as rnk
            from ret_grid_step1
            --where cust_name is not null
            group by 1,2,created_at
        ) as b
        on a.email = b.email
        where b.rnk = 1
        and a.email <> '';
$$ language plpgsql;

0 个答案:

没有答案