我学习和练习sql已经有6个月了。我已经准备好了,承认我要为它哑口无言,而我的大脑却无法理解它的大部分模式。我试图创建一个透视表。关于这个主题的简单文献并不多,我找到的一个资料来源谈到了创建多维数据集和基本实体属性值(EAV)逻辑。。不管那意味着什么。

name        action  pagecount
-------------------------------
Company A   PRINT    3
Company A   PRINT    2
Company A   PRINT    3
Company B   EMAIL    6
Company B   PRINT    2
Company B   PRINT    2
Company B   PRINT    1
Company A   PRINT    3

我想交叉制表(这是正确的术语吗?)列name,列总数action,列总数pagecount
 name        action_PRINT   action_EMAIL       pagecount_PRINT      pagecount_EMAIL
--------------------------------------------------------------------------------
Company A   4                0                 11                       0
Company B   3                1                 5                        6

最佳答案

这种类型的操作称为PIVOT但MySQL没有pivot函数,因此需要使用聚合函数和CASE语句复制它。
可以使用以下命令生成结果:

select name,
  sum(case when action = 'PRINT' then 1 else 0 end) action_print,
  sum(case when action = 'EMAIL' then 1 else 0 end) action_email,
  sum(case when action = 'PRINT' then pagecount else 0 end) pagecount_print,
  sum(case when action = 'EMAIL' then pagecount else 0 end) pagecount_email
from yourtable
group by name

SQL Fiddle with Demo
结果将是:
|      NAME | ACTION_PRINT | ACTION_EMAIL | PAGECOUNT_PRINT | PAGECOUNT_EMAIL |
-------------------------------------------------------------------------------
| Company A |            4 |            0 |              11 |               0 |
| Company B |            3 |            1 |               5 |               6 |

10-05 17:54