【问题标题】:SQL - create pivot table/cross tab from raw dataSQL - 从原始数据创建数据透视表/交叉表
【发布时间】:2014-07-20 02:11:23
【问题描述】:

使用 SQL 将平面表的布局转换为交叉表/数据透视表的最佳方法是什么。

无需计算。 原始表的第一列将是 PV 表中的第一列,第二列 raw 将被分配到 PVtable 中的列(12 个不同的值)中。值将是原始表中的第三列。

我在转换此布局时遇到了困难,我想我为此付出了很多努力,使其难以阅读/维护。

有人知道怎么做吗? 非常感谢!

示例,如下 原始:

指数排名分数 1 1 59 1 2 15 1 3 17 1 4 7 1 5 56 1 6 13 1 7 7 1 8 3 1 9 7 1 10 10 1 11 2 1 12 181 2 2 16 2 3 19 2 4 7 2 5 79 2 6 20 2 7 13 2 8 5 2 9 10 2 10 18 2 11 5 2 12 268 3 3 12 3 4 6 3 5 56 3 6 10 3 7 9 3 8 5 3 9 8 3 10 17 3 11 3 3 12 219 4 4 1 4 5 19 4 6 4 4 7 3 4 8 2 4 9 6 4 10 5 4 11 1 4 12 102

PV 表:

秩 指数 1 2 3 4 5 6 7 8 9 10 11 12 1 59 15 17 7 56 13 7 3 7 10 2 181 2 - 16 19 7 79 20 13 5 10 18 5 267 3 - - 12 6 56 10 9 5 8 17 3 219 4 - - - 1 19 4 3 2 6 5 1 101 5 - - - - 0 0 0 0 0 0 0 0 6 - - - - - 0 0 0 0 0 0 0 7 - - - - - - 0 0 0 0 0 0 8 - - - - - - - 0 0 0 0 0 9 - - - - - - - - 0 0 0 0 10 - - - - - - - - - 0 0 0 11 - - - - - - - - - - 0 0 12 - - - - - - - - - - - 0

【问题讨论】:

  • 为什么最后一行都是零?

标签: sql pivot-table


【解决方案1】:

适用于几乎任何数据库的规范方法是条件聚合方法:

select indx
       max(case when rank = 1 then score end) as rank1,
       max(case when rank = 2 then score end) as rank2,
       . . .
       max(case when rank = 12 then score end) as rank12
from table t
group by indx
order by indx;

但是,在您的示例中,不清楚 5 及以上的哪些索引都具有 0 的值。

编辑:

如果您希望 5+ 的值为 0 并从 1-2 中获取值,则使用 left outer join 并更改 max() 中的逻辑:

select n.n as indx,
       max(case when rank = 1 then score end) as rank1,
       max(case when rank = 2 then score end) as rank2,
       . . .
       max(case when rank = 12 then score when n.n >= 12 then 0 end) as rank12
from (select 1 as n union all select 2 union all select 3 union all select 4 union all
      select 5 union all select 6 union all select 7 union all select 8 union all
      select 9 union all select 10 union all select 11 union all select 12
     ) n left outer join
     table t
     on n.n = t.indx
group by n.n
order by n.n;

【讨论】:

  • 是的,在我的示例中,索引 > 5 被视为 0。我使用的与您发布的相同,但没有 max() 函数,还有带有 GROUP BY 其他 2 个字段的 n!是在生成正确的数据,但不是作为数据透视表!抱歉,我不能投票:/ 谢谢!
猜你喜欢
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2012-04-16
  • 1970-01-01
  • 2010-10-17
相关资源
最近更新 更多