Search code examples
sqlpostgresqlgroup-bysumunpivot

Rotate results with SQL


I'm using Blazer have the following query:

SELECT 
sum(active_paid_users_count) as Active,
sum(inactive_paid_users_count) as Inactive,
sum(free_users_count) as Free
FROM accounts
WHERE
  trialing = false
  AND
  cancelled = false

This produces the following table:

sql results

I'd like to rotate this table so that I can get a pie chart result out of Blazer. It would end up looking like this:

Type     Count
active      31
inactive    76
free       190

Solution

  • You can unpivot with a a lateral join. The upside is that this requires a single table scan:

    select v.type, v.cnt
    from (
        select 
            sum(active_paid_users_count) as active,
            sum(inactive_paid_users_count) as inactive,
            sum(free_users_count) as free
        from accounts
        where trialing = false and cancelled = false
    ) t
    cross join lateral (
        values ('active', t.active), ('inactive', t.inactive), ('free', t.free)
    ) as v(type, cnt)