DROP VIEW IF EXISTS v_analytics_orders2;

CREATE VIEW v_analytics_orders2 AS
    SELECT
        orders.id as order_id,
        inserted AS order_date,
        delivered,
        newsletter,
        credit_invoice,
        canceled,
        reminder,
        delivered_date,
        orders.country_code,
        language,
        delivery_country_code,
        delivery_method,
        delivery_price,
        customer_type,
        payment_type,
        currency,
        exchange_rate,
        exchange_rate_eur,
        invoice_id,
        contract_customer_id,
        vat_number,
        cancels_order_id,
        cancelled_by_order_id,
        reseller_store,
        order_sum,
        order_sum / exchange_rate AS order_sum_sek,
        email,
        phone,
        billing_address.address1 as billing_address_address1,
        billing_address.address2 as billing_address_address2,
        billing_address.company_name as billing_address_company_name,
        billing_address.country_code as billing_address_country_code,
        billing_address.city as billing_address_city,
        billing_address.zipcode as billing_address_zipcode,
        billing_address.first_name as billing_address_first_name,
        billing_address.last_name as billing_address_last_name,
        billing_address.state as billing_address_state,
        delivery_address.address1 as delivery_address_address1,
        delivery_address.address2 as delivery_address_address2,
        delivery_address.company_name as delivery_address_company_name,
        delivery_address.country_code as delivery_address_country_code,
        delivery_address.city as delivery_address_city,
        delivery_address.zipcode as delivery_address_zipcode,
        delivery_address.first_name as delivery_address_first_name,
        delivery_address.last_name as delivery_address_last_name,
        delivery_address.state as delivery_address_state
    FROM orders
    JOIN addresses billing_address ON billing_address.id = orders.billing_address_id
    LEFT JOIN addresses delivery_address ON delivery_address.id = orders.delivery_address_id
    WHERE paid = 1;

GRANT SELECT ON v_analytics_orders2 TO datastudio;
