【问题标题】:Pivot Table with Redshift (PostgreSQL) with Count使用 Redshift (PostgreSQL) 和计数的数据透视表
【发布时间】:2017-07-27 09:04:36
【问题描述】:

我在使用 Redshift 时面临挑战: 我正在尝试将行动态移动到列中并按计数聚合,但是我注意到数据透视表功能仅在 PostgreSQL 9 中可用。

您知道如何执行以下操作吗?

 index   fruit     color 
 1       apple     red           
 2       apple     yellow           
 2       banana    blue           
 2       banana    blue           
 3       banana    blue     
 3       banana    green     
 3       pear      green     
 3       pear      red           

到:

 index   red       yellow    blue    green 
 1       1         0         0       0
 2       0         1         2       0
 3       1         0         1       2

本质上,对每个 id 的颜色进行分组和计数(水果并不那么重要,尽管我稍后会将其用作过滤器)。

注意:我可能还想稍后进行二进制转换(即 0 表示 0 和 1 如果 > 0)

编辑:如果上述方法不可行,有什么方法可以代替吗?

 index   color     count     
 1       red       1        
 1       yellow    0           
 1       blue      0
 1       green     0 
 2       red       0        
 2       yellow    1           
 2       blue      2
 2       green     0
 3       red       1         
 3       yellow    0           
 3       blue      1
 3       green     2

(同样蓝色、黄色、蓝色和绿色应该是动态的)

【问题讨论】:

    标签: sql pivot amazon-redshift


    【解决方案1】:

    对于编辑,您可以这样做

    select x.index, x.color, sum(case when y.index is not null then 1 else 0 end) as count
    from 
    ((select index
    from [table]
    group by index
    order by index) a
    inner join 
    (select color
    from [table]
    group by color
    order by color) b
    on 1 = 1) x
    left outer join
    [table] y
    on x.index = y.index
    and x.color = y.color
    group by x.index, x.color
    order by x.index, x.color
    

    【讨论】:

      【解决方案2】:

      如果 PIVOT 在 Redshift 中不可用,那么您总是可以只使用标准的数据透视查询:

      SELECT
          index,
          SUM(CASE WHEN color = 'red'    THEN 1 ELSE 0 END) AS red,
          SUM(CASE WHEN color = 'yellow' THEN 1 ELSE 0 END) AS yellow,
          SUM(CASE WHEN color = 'blue'   THEN 1 ELSE 0 END) AS blue,
          SUM(CASE WHEN color = 'green'  THEN 1 ELSE 0 END) AS green
      FROM yourTable
      GROUP BY index
      

      【讨论】:

      • 谢谢!但这意味着我必须提前知道“红色”、“黄色”、“蓝色”等?如果我不这样做呢?
      • 那么您需要为此使用动态 SQL,which appears to be not supported for Redshift
      • Redshift 中没有哪个?
      猜你喜欢
      • 1970-01-01
      • 2014-01-04
      • 2022-01-24
      • 2022-01-15
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      相关资源
      最近更新 更多