MySQL数据透视表

时间:2011-10-06 13:20:14

标签: mysql pivot

如果我有一个类似于这样的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可能会有所不同,因此输出列数量应该反映出来,每个action / pagecount对的一列,然后是每company_name次点击次数。我不确定这是否被称为数据透视表,但有人建议?

10 个答案:

答案 0 :(得分:218)

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

有关如何实现这一目标的精彩教程,请访问: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

行(EMAILPRINT x pages)类似于条件。主要分组是company_name

为了设置条件,这个使用CASE语句而是大声呼喊。为了按某种方式进行分组,请使用... GROUP BY

提供此数据透视的基本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语句中定义的条件就越多。

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

关于此主题的一些其他链接:

答案 1 :(得分:75)

我的解决方案是在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

答案 2 :(得分:61)

对于MySQL,您可以直接在SUM()函数中添加条件,它将评估为布尔01 ,因此您可以根据根据您的条件,不使用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

答案 3 :(得分:32)

对于动态数据透视,请将GROUP_CONCATCONCAT一起使用。 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;

<强> DEMO HERE

答案 4 :(得分:21)

使用boolean logic stardard-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;

SQL Fiddle.

如何?

TRUE OR NULL收益TRUE FALSE OR NULL会产生NULL NULL OR NULL会产生NULL 并且COUNT仅计算非空值。瞧。

答案 5 :(得分:10)

有一个名为MySQL Pivot表生成器的工具,它可以帮助您创建基于Web的数据透视表,以后可以导出到excel(如果您愿意)。如果您的数据位于单个表或多个表中,它可以工作。

您需要做的就是指定列的数据源(它支持动态列),行,表的主体中的值和表关系(如果有的话) MySQL Pivot Table

此工具的主页为http://mysqlpivottable.net

答案 6 :(得分:8)

正确答案是:

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

答案 7 :(得分:3)

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 ;

答案 8 :(得分:0)

一种选择是组合使用 CASE..WHEN语句是多余的,用于MySQL数据库的聚合,并动态考虑所需的查询生成< / strong>,以及为结果集 获取正确的列标题 ,如以下代码块所示:

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

答案 9 :(得分:0)

SELECT company_name, 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 "print 1 PAGE",
SUM(CASE WHEN ACTION = 'Print' AND pagecount = 2 THEN 1 ELSE 0 END) AS "print 2 PAGE",
SUM(CASE WHEN ACTION = 'Print' AND pagecount = 3 THEN 1 ELSE 0 END) AS "print 2 PAGE"
FROM test1 GROUP BY company_name;