将当前数据与一年前的数据进行比较,同一天(Postgres)

时间:2016-01-18 09:18:00

标签: postgresql

我正在尝试返回当前日期的订单数据和一年前同一日期的订单。 我的想法是创建两个类似的表并通过添加WHERE子句合并日期。但似乎行不通。 你能看看我的代码,看看你是否发现了错误吗? 我的结果完全是空白的。 非常感谢!

 WITH 
orders_channels AS
(SELECT
    'BLH' AS brand,
    date_trunc('week', date)::date AS date,
    channel,
    order_type,
    case when (date_trunc('week', date)::date = current_date -  interval '1 day') then 'current' 
    else 'previous' end 
    as week_type,
    sum(orders) AS orders
FROM
    de_data.orders_daily_channel_attribution_dashboard 
WHERE
    date > date_trunc('day', current_date) - interval '1 day'

GROUP BY 1,2,3,4),

wow_orders_channels AS
(SELECT
    'BLH' AS brand,
    date_trunc('week', date)::date AS date,
    channel,
    order_type,
    case when (date_trunc('week', date)::date = current_date -  interval '1 day') then 'current' 
    else 'previous' end 
    as week_type,
    sum(orders) AS orders
FROM
    de_data.orders_daily_channel_attribution_dashboard 
WHERE
    date >= date_trunc('week', current_date) - INTERVAL '1 year'

GROUP BY 1,2,3,4)

SELECT
    *
FROM
    (SELECT
        o.brand,
        date_trunc('week', o.date)::date as week,
        'SEO_ACQ' AS name,
        o.orders,
        wow.orders as wow_orders

    FROM
        orders_channels o 
        join wow_orders_channels wow on wow.date = o.date - interval '1 year' and o.order_type = wow.order_type
       where
         o.channel = 'SEO'
         AND o.order_type = 'ACQUISITION'
    UNION ALL
    SELECT
        o.brand,
        date_trunc('week', o.date) as week,
        'CRM_ORDERS' AS name,
        SUM(o.orders),
        sum(wow.orders) as wow_orders
    FROM
        orders_channels o 
        join wow_orders_channels wow on wow.date = o.date - interval '1 year' and o.order_type = wow.order_type

    WHERE
         o.channel = 'CRM'
    GROUP BY 1,2,3) x
ORDER BY 3,2

0 个答案:

没有答案