SQL: Stacking columns by bucketed metrics

251 views Asked by At

So I'm using SQL with a charting tool, and I can't get buckets of my metrics to reflect as proportions of a total in a y-axis (as stacked columns) with the metrics in the x-axis.

Example: Metrics (x-axis values) should be "Job Count", "Visits", "Apps", and "Spend". Each one should have a stacked column based on the following bucket of the Visits metrics:

1-2 Visits, 3-4 Visits, 5-7 Visits, 8-10 Visits, 11-15 Visits, 16-25 Visits, and 25+ Visits.

My query is as follows:

select
  alias.grp as Bucket
  , count(alias.jobid) as Number_Of_Jobs_by_Bucket
  , sum(alias.total_visits) as Visits_by_Bucket
  , sum(alias.spend) as Spend_by_Bucket
  , sum(alias.Total_applications) as Apps_by_Bucket
from
  (
    select
      analytics.jobid
      , case
        when sum(analytics.visits) >= 1
        and sum(analytics.visits) <= 2
          then 'A: 1-2 Visits'
        when sum(analytics.visits) > 2
        and sum(analytics.visits) <= 4
          then 'B: 3-4 Visits'
        when sum(analytics.visits) > 4
        and sum(analytics.visits) <= 7
          then 'C: 5-7 Visits'
        when sum(analytics.visits) > 7
        and sum(analytics.visits) <= 10
          then 'D: 8-10 Visits'
        when sum(analytics.visits) > 10
        and sum(analytics.visits) <= 15
          then 'E: 11-15 Visits'
        when sum(analytics.visits) > 15
        and sum(analytics.visits) <= 25
          then 'F: 16-25 Visits'
        when sum(analytics.visits) > 25
          then 'G: 25+ Visits'
      end as grp
      , sum(analytics.visits) as Total_Visits
      , sum(analytics.total_spend100)/100 as Spend
      , sum(analytics.applications) as Total_Applications
    from
      analytics
    where
      visits > 0
    group by
      analytics.jobid
  )
  as alias
where
  alias.total_visits > 0
group by
  alias.grp
order by
  alias.grp

So I'm trying to use a subquery to define the buckets but cannot get percentages of each metric by bucket to fall into a Y-Axis (due to it being a text value). Ideally, I'd show four columns (by metrics) with each one showing for example 10% for the first bucket, 25% for the second bucket, 4% for the third bucket, etc.

Any thoughts on refining the query to support this?

Thanks!

0

There are 0 answers