使用 SQL 旋转结果

Rotate results with SQL

我正在使用 Blazer 有以下查询:

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

这会产生以下结果 table:

我想旋转这个 table,这样我就可以从 Blazer 中得到一个饼图结果。它最终看起来像这样:

Type     Count
active      31
inactive    76
free       190

几个工会应该为您解决这个问题。

SELECT 'Active'                     AS Type, 
     , sum(active_paid_users_count) AS Count
FROM accounts
WHERE
  trialing = false
  AND
  cancelled = false

UNION

SELECT 'Inactive'                     AS Type, 
     , sum(inactive_paid_users_count) AS Count
FROM accounts
WHERE
  trialing = false
  AND
  cancelled = false

UNION

SELECT 'Free'                AS Type, 
     , sum(free_users_count) AS Count
FROM accounts
WHERE
  trialing = false
  AND
  cancelled = false

您可以使用横向连接来取消透视。好处是这需要单次 table 扫描:

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)