如果我有一个MySQL表,看起来像这样:

company_name    action  pagecount
-------------------------------
Company A       PRINT   3
Company A       PRINT   2
Company A       PRINT   3
Company B       EMAIL   
Company B       PRINT   2
Company B       PRINT   2
Company B       PRINT   1
Company A       PRINT   3

是否可以运行一个MySQL查询来得到这样的输出:

company_name    EMAIL   PRINT 1 pages   PRINT 2 pages   PRINT 3 pages
-------------------------------------------------------------
CompanyA        0       0               1               3
CompanyB        1       1               2               0

其思想是pagecount可以变化,因此输出列的数量应该反映这一点,一个列对应每个操作/pagecount对,然后是每个company_name的点击数。我不确定这是否叫做数据透视表但有人建议这样做?


当前回答

一种选择是结合使用CASE..WHEN语句在MySQL数据库的聚合中是冗余的,并动态考虑所需的查询生成,同时为结果集获得适当的列标题,如下代码块所示:

SET @sql = NULL;

SELECT GROUP_CONCAT(
             CONCAT('SUM( `action` = ''', action, '''',pc0,' ) AS ',action,pc1)
       )
  INTO @sql
  FROM 
  ( 
   SELECT DISTINCT `action`, 
          IF(`pagecount` IS NULL,'',CONCAT('page',`pagecount`)) AS pc1,
          IF(`pagecount` IS NULL,'',CONCAT(' AND `pagecount` = ', pagecount, '')) AS pc0
     FROM `tab` 
    ORDER BY CONCAT(action,pc0) 
  ) t;

SET @sql = CONCAT('SELECT company_name,',@sql,' FROM `tab` GROUP BY company_name'); 
SELECT @sql; 

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Demo

其他回答

我的解决方案是在T-SQL没有任何枢轴:

SELECT
    CompanyName,  
    SUM(CASE WHEN (action='EMAIL') THEN 1 ELSE 0 END) AS Email,
    SUM(CASE WHEN (action='PRINT' AND pagecount=1) THEN 1 ELSE 0 END) AS Print1Pages,
    SUM(CASE WHEN (action='PRINT' AND pagecount=2) THEN 1 ELSE 0 END) AS Print2Pages,
    SUM(CASE WHEN (action='PRINT' AND pagecount=3) THEN 1 ELSE 0 END) AS Print3Pages
FROM 
    Company
GROUP BY 
    CompanyName
select t3.name, sum(t3.prod_A) as Prod_A, sum(t3.prod_B) as Prod_B, sum(t3.prod_C) as    Prod_C, sum(t3.prod_D) as Prod_D, sum(t3.prod_E) as Prod_E  
from
(select t2.name as name, 
case when t2.prodid = 1 then t2.counts
else 0 end  prod_A, 

case when t2.prodid = 2 then t2.counts
else 0 end prod_B,

case when t2.prodid = 3 then t2.counts
else 0 end prod_C,

case when t2.prodid = 4 then t2.counts
else 0 end prod_D, 

case when t2.prodid = "5" then t2.counts
else 0 end prod_E

from 
(SELECT partners.name as name, sales.products_id as prodid, count(products.name) as counts
FROM test.sales left outer join test.partners on sales.partners_id = partners.id
left outer join test.products on sales.products_id = products.id 
where sales.partners_id = partners.id and sales.products_id = products.id group by partners.name, prodid) t2) t3

group by t3.name ;

这基本上就是一个数据透视表。

关于如何做到这一点,可以在这里找到一个很好的教程:http://www.artfulsoftware.com/infotree/qrytip.php?id=78

我建议你阅读这篇文章,并根据你的需要调整这个解决方案。

更新

在上面的链接目前不可用之后,我觉得有必要为所有在这里搜索mysql pivot答案的人提供一些额外的信息。它确实有大量的信息,我不会把所有的东西都放在这里(甚至更多,因为我只是不想复制他们庞大的知识),但我会给出一些建议,关于如何处理sql方式的数据透视表,通常是用peku的例子,他首先提出了这个问题。

也许这个链接很快就会回来,我会留意的。

电子表格的方式…

许多人只是使用MSExcel、OpenOffice或其他电子表格工具来实现这一目的。这是一个有效的解决方案,只需将数据复制到那里,并使用GUI提供的工具来解决这个问题。

但是…这不是问题所在,它甚至可能导致一些缺点,比如如何将数据输入电子表格,有问题的缩放等等。

SQL的方式…

假设他的表格是这样的:

CREATE TABLE `test_pivot` (
  `pid` bigint(20) NOT NULL AUTO_INCREMENT,
  `company_name` varchar(32) DEFAULT NULL,
  `action` varchar(16) DEFAULT NULL,
  `pagecount` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=MyISAM;

现在看看他/她想要的桌子:

company_name    EMAIL   PRINT 1 pages   PRINT 2 pages   PRINT 3 pages
-------------------------------------------------------------
CompanyA        0       0               1               3
CompanyB        1       1               2               0

行(EMAIL, PRINT x pages)类似于条件。主要的分组是根据company_name。

为了设置条件,需要使用case语句。为了根据某些东西进行分组,嗯,使用…集团。

提供这个枢轴的基本SQL可以是这样的:

SELECT  P.`company_name`,
    COUNT(
        CASE 
            WHEN P.`action`='EMAIL' 
            THEN 1 
            ELSE NULL 
        END
    ) AS 'EMAIL',
    COUNT(
        CASE 
            WHEN P.`action`='PRINT' AND P.`pagecount` = '1' 
            THEN P.`pagecount` 
            ELSE NULL 
        END
    ) AS 'PRINT 1 pages',
    COUNT(
        CASE 
            WHEN P.`action`='PRINT' AND P.`pagecount` = '2' 
            THEN P.`pagecount` 
            ELSE NULL 
        END
    ) AS 'PRINT 2 pages',
    COUNT(
        CASE 
            WHEN P.`action`='PRINT' AND P.`pagecount` = '3' 
            THEN P.`pagecount` 
            ELSE NULL 
        END
    ) AS 'PRINT 3 pages'
FROM    test_pivot P
GROUP BY P.`company_name`;

这将很快提供所需的结果。这种方法的主要缺点是,数据透视表中的行越多,需要在SQL语句中定义的条件就越多。

这也是可以处理的,因此人们倾向于使用准备好的语句、例程、计数器等。

关于这个主题的其他链接:

http://anothermysqldba.blogspot.de/2013/06/pivot-tables-example-in-mysql.html http://www.codeproject.com/Articles/363339/Cross-Tabulation-Pivot-Tables-with-MySQL http://datacharmer.org/downloads/pivot_tables_mysql_5.pdf https://codingsight.com/pivot-tables-in-mysql/

一种选择是结合使用CASE..WHEN语句在MySQL数据库的聚合中是冗余的,并动态考虑所需的查询生成,同时为结果集获得适当的列标题,如下代码块所示:

SET @sql = NULL;

SELECT GROUP_CONCAT(
             CONCAT('SUM( `action` = ''', action, '''',pc0,' ) AS ',action,pc1)
       )
  INTO @sql
  FROM 
  ( 
   SELECT DISTINCT `action`, 
          IF(`pagecount` IS NULL,'',CONCAT('page',`pagecount`)) AS pc1,
          IF(`pagecount` IS NULL,'',CONCAT(' AND `pagecount` = ', pagecount, '')) AS pc0
     FROM `tab` 
    ORDER BY CONCAT(action,pc0) 
  ) t;

SET @sql = CONCAT('SELECT company_name,',@sql,' FROM `tab` GROUP BY company_name'); 
SELECT @sql; 

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Demo

正确答案是:

select table_record_id,
group_concat(if(value_name='note', value_text, NULL)) as note
,group_concat(if(value_name='hire_date', value_text, NULL)) as hire_date
,group_concat(if(value_name='termination_date', value_text, NULL)) as termination_date
,group_concat(if(value_name='department', value_text, NULL)) as department
,group_concat(if(value_name='reporting_to', value_text, NULL)) as reporting_to
,group_concat(if(value_name='shift_start_time', value_text, NULL)) as shift_start_time
,group_concat(if(value_name='shift_end_time', value_text, NULL)) as shift_end_time
from other_value
where table_name = 'employee'
and is_active = 'y'
and is_deleted = 'n'
GROUP BY table_record_id