Creating Models from SQL
Last updated
Was this helpful?
Was this helpful?
SELECT *
FROM public.orders
WHERE status = 'completed'SELECT
o.order_id,
o.order_date,
o.total_amount,
c.customer_name,
c.customer_tier
FROM public.orders o
JOIN public.customers c ON o.customer_id = c.customer_idWITH monthly_stats AS (
SELECT
customer_id,
DATE_TRUNC('month', order_date) as month,
SUM(amount) as monthly_revenue,
COUNT(*) as order_count
FROM public.orders
GROUP BY customer_id, DATE_TRUNC('month', order_date)
)
SELECT
customer_id,
month,
monthly_revenue,
order_count,
AVG(monthly_revenue) OVER (
PARTITION BY customer_id
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) as rolling_avg_revenue
FROM monthly_statsSELECT
c.customer_id,
c.customer_name,
c.signup_date,
c.tier,
COUNT(DISTINCT o.order_id) as total_orders,
SUM(o.amount) as lifetime_value,
MAX(o.order_date) as last_order_date
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name, c.signup_date, c.tierSELECT
DATE_TRUNC('day', event_timestamp) as event_date,
event_type,
COUNT(*) as event_count,
COUNT(DISTINCT user_id) as unique_users
FROM events
WHERE event_timestamp >= CURRENT_DATE - INTERVAL '90 days'
GROUP BY DATE_TRUNC('day', event_timestamp), event_typeSELECT *
FROM transactions
WHERE status = 'completed'
AND amount > 0
AND test_mode = false