Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 38 additions & 27 deletions dbt/models/marts/core/fct_orders.sql
Original file line number Diff line number Diff line change
@@ -1,38 +1,49 @@
-- Core fact table for orders with all enrichments
with orders as (
select * from {{ ref('int_orders_enriched') }}

select * from {{ ref('stg_orders') }}

),

customers as (
select * from {{ ref('stg_customers') }}
order_items as (

select * from {{ ref('fct_order_items') }}

),

order_items_summary as (

select
order_id,

sum(product_price) as order_total,
count(*) as item_count,
avg(product_price) as avg_item_price

from order_items
group by 1

),

final as (

select
o.order_id,
o.customer_id,
c.first_name || ' ' || c.last_name as customer_name,
o.order_date,
o.status,
o.is_completed,
o.is_returned,
o.total_items,
o.total_quantity,
o.items_subtotal,
o.distinct_categories,
o.credit_card_amount,
o.coupon_amount,
o.bank_transfer_amount,
o.gift_card_amount,
o.total_payment_amount,
o.payment_count,
orders.order_id,
orders.customer_id,
orders.order_date,
orders.status,

order_items_summary.order_total as amount,
order_items_summary.item_count,
order_items_summary.avg_item_price,
case
when o.total_payment_amount >= 500 then 'Large'
when o.total_payment_amount >= 20 then 'Medium'
else 'Small'
end as order_size_bucket
from orders o
left join customers c on o.customer_id = c.customer_id
when order_items_summary.item_count >= 5 then 'large'
when order_items_summary.item_count >= 2 then 'medium'
else 'small'
end as order_size_category

from orders
left join order_items_summary on orders.order_id = order_items_summary.order_id

)

select * from final