| 1 | DROP VIEW IF EXISTS public.v_customer_usage_360_summary;
|
|---|
| 2 |
|
|---|
| 3 | CREATE VIEW public.v_customer_usage_360_summary AS
|
|---|
| 4 | SELECT
|
|---|
| 5 | c.customer_id,
|
|---|
| 6 | CASE WHEN c.customer_type = 'business' THEN c.company_name ELSE c.first_name || ' ' || c.last_name END AS customer_name,
|
|---|
| 7 | a.account_number,
|
|---|
| 8 | s.subscription_id,
|
|---|
| 9 | s.subscription_number,
|
|---|
| 10 | p.plan_name,
|
|---|
| 11 | MIN(uad.usage_date) AS first_usage_date,
|
|---|
| 12 | MAX(uad.usage_date) AS last_usage_date,
|
|---|
| 13 | COUNT(*) AS active_usage_days,
|
|---|
| 14 | ROUND(SUM(uad.total_call_seconds)::numeric / 60.0, 2) AS total_call_minutes,
|
|---|
| 15 | SUM(uad.total_sms_count) AS total_sms,
|
|---|
| 16 | ROUND(SUM(uad.total_data_mb) / 1024.0, 2) AS total_data_gb,
|
|---|
| 17 | ROUND(AVG(uad.total_data_mb) / 1024.0, 4) AS average_daily_data_gb,
|
|---|
| 18 | SUM(uad.total_charge_amount) AS total_usage_charges,
|
|---|
| 19 | DENSE_RANK() OVER (ORDER BY SUM(uad.total_data_mb) DESC) AS data_usage_rank
|
|---|
| 20 | FROM public.customers c
|
|---|
| 21 | JOIN public.accounts a ON a.customer_id = c.customer_id
|
|---|
| 22 | JOIN public.subscriptions s ON s.account_id = a.account_id
|
|---|
| 23 | JOIN public.plans p ON p.plan_id = s.plan_id
|
|---|
| 24 | JOIN public.usage_aggregates_daily uad ON uad.subscription_id = s.subscription_id
|
|---|
| 25 | GROUP BY c.customer_id, c.customer_type, c.company_name, c.first_name, c.last_name,
|
|---|
| 26 | a.account_number, s.subscription_id, s.subscription_number, p.plan_name;
|
|---|
| 27 |
|
|---|