如果我有一个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的点击数。我不确定这是否叫做数据透视表但有人建议这样做?


当前回答

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 ;

其他回答

对于动态枢轴,使用GROUP_CONCAT和CONCAT。 GROUP_CONCAT函数使用各种选项将组中的字符串连接到一个字符串中。

SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN action = "',
      action,'"  AND ', 
           (CASE WHEN pagecount IS NOT NULL 
           THEN CONCAT("pagecount = ",pagecount) 
           ELSE pagecount IS NULL END),
      ' THEN 1 ELSE 0 end) AS ',
      action, IFNULL(pagecount,'')
      
    )
  )
INTO @sql
FROM
  t;

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

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

演示

对于MySQL,您可以直接将条件放在SUM()函数中,它将被计算为布尔0或1,因此您可以根据您的条件计算,而无需使用IF/CASE语句

SELECT
    company_name,  
    SUM(action = 'EMAIL')AS Email,
    SUM(action = 'PRINT' AND pagecount = 1)AS Print1Pages,
    SUM(action = 'PRINT' AND pagecount = 2)AS Print2Pages,
    SUM(action = 'PRINT' AND pagecount = 3)AS Print3Pages
FROM t
GROUP BY company_name

DEMO

使用布尔逻辑的标准sql版本:

SELECT company_name
     , COUNT(action = 'EMAIL' OR NULL) AS "Email"
     , COUNT(action = 'PRINT' AND pagecount = 1 OR NULL) AS "Print 1 pages"
     , COUNT(action = 'PRINT' AND pagecount = 2 OR NULL) AS "Print 2 pages"
     , COUNT(action = 'PRINT' AND pagecount = 3 OR NULL) AS "Print 3 pages"
FROM   tbl
GROUP  BY company_name;

db < >小提琴 老sqlfiddle

How?

TRUE或NULL产生TRUE。 FALSE或NULL产生NULL。 NULL或NULL产生NULL。 COUNT只计算非空值。瞧。

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/