246

我试图搜索帖子,但我只找到了 SQL Server/Access 的解决方案。我需要 MySQL (5.X) 中的解决方案。

我有一个包含 3 列的表(称为历史记录):hostid、itemname、itemvalue。
如果我做一个选择(select * from history),它将返回

   +--------+----------+-----------+
   | hostid | itemname | itemvalue |
   +--------+----------+-----------+
   |   1    |    A     |    10     |
   +--------+----------+-----------+
   |   1    |    B     |     3     |
   +--------+----------+-----------+
   |   2    |    A     |     9     |
   +--------+----------+-----------+
   |   2    |    c     |    40     |
   +--------+----------+-----------+

如何查询数据库以返回类似

   +--------+------+-----+-----+
   | hostid |   A  |  B  |  C  |
   +--------+------+-----+-----+
   |   1    |  10  |  3  |  0  |
   +--------+------+-----+-----+
   |   2    |   9  |  0  |  40 |
   +--------+------+-----+-----+
4

13 回答 13

325

我将添加一个更长更详细的解释来解决这个问题。如果太长,我很抱歉。


我将从您给出的基础开始,并使用它来定义我将在本文的其余部分使用的几个术语。这将是基表

select * from history;

+--------+----------+-----------+
| hostid | itemname | itemvalue |
+--------+----------+-----------+
|      1 | A        |        10 |
|      1 | B        |         3 |
|      2 | A        |         9 |
|      2 | C        |        40 |
+--------+----------+-----------+

这将是我们的目标,漂亮的数据透视表

select * from history_itemvalue_pivot;

+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 |    0 |
|      2 |    9 |    0 |   40 |
+--------+------+------+------+

列中的值history.hostid将成为数据透视表中的y 值。列中的值history.itemname将变为x 值(出于显而易见的原因)。


当我必须解决创建数据透视表的问题时,我使用三步过程(可选的第四步)来解决它:

  1. 选择感兴趣的列,即y 值x 值
  2. 用额外的列扩展基表——每个x 值一列
  3. 对扩展表进行分组和聚合——每个y 值一组
  4. (可选)美化聚合表

让我们将这些步骤应用于您的问题,看看我们得到了什么:

第 1 步:选择感兴趣的列。在所需结果中,hostid提供y 值itemname提供x 值

第 2 步:用额外的列扩展基表。我们通常需要每个 x 值一列。回想一下我们的 x 值列是itemname

create view history_extended as (
  select
    history.*,
    case when itemname = "A" then itemvalue end as A,
    case when itemname = "B" then itemvalue end as B,
    case when itemname = "C" then itemvalue end as C
  from history
);

select * from history_extended;

+--------+----------+-----------+------+------+------+
| hostid | itemname | itemvalue | A    | B    | C    |
+--------+----------+-----------+------+------+------+
|      1 | A        |        10 |   10 | NULL | NULL |
|      1 | B        |         3 | NULL |    3 | NULL |
|      2 | A        |         9 |    9 | NULL | NULL |
|      2 | C        |        40 | NULL | NULL |   40 |
+--------+----------+-----------+------+------+------+

请注意,我们没有更改行数——我们只是添加了额外的列。还要注意NULLs 的模式 - 具有itemname = "A"新列的非空值的行A和其他新列的空值。

步骤 3:对扩展表进行分组和聚合。我们需要group by hostid,因为它提供了 y 值:

create view history_itemvalue_pivot as (
  select
    hostid,
    sum(A) as A,
    sum(B) as B,
    sum(C) as C
  from history_extended
  group by hostid
);

select * from history_itemvalue_pivot;

+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 | NULL |
|      2 |    9 | NULL |   40 |
+--------+------+------+------+

(请注意,我们现在每个 y 值都有一行。) 好的,我们快到了!我们只需要摆脱那些丑陋NULL的s。

第四步:美化。我们只是要用零替换任何空值,以便结果集更好看:

create view history_itemvalue_pivot_pretty as (
  select 
    hostid, 
    coalesce(A, 0) as A, 
    coalesce(B, 0) as B, 
    coalesce(C, 0) as C 
  from history_itemvalue_pivot 
);

select * from history_itemvalue_pivot_pretty;

+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 |    0 |
|      2 |    9 |    0 |   40 |
+--------+------+------+------+

我们已经完成了——我们已经使用 MySQL 构建了一个漂亮、漂亮的数据透视表。


应用此过程时的注意事项:

  • 在额外的列中使用什么值。我itemvalue在这个例子中使用
  • 在额外的列中使用什么“中性”值。我用过NULL,但也可能是0or "",这取决于你的具体情况
  • 分组时使用什么聚合函数。我使用过sum,但countmax经常使用(max在构建已分布在多行的单行“对象”时经常使用)
  • 对 y 值使用多列。此解决方案不仅限于对 y 值使用单个列 - 只需将额外的列插入group by子句(不要忘记select它们)

已知限制:

  • 此解决方案不允许数据透视表中有 n 列——扩展基表时需要手动添加每个数据透视列。所以对于 5 或​​ 10 个 x 值,这个解决方案很好。100,不是很好。有一些使用存储过程生成查询的解决方案,但它们很难看且难以正确处理。当数据透视表需要有很多列时,我目前不知道解决此问题的好方法。
于 2012-03-12T13:35:18.207 回答
67
SELECT 
    hostid, 
    sum( if( itemname = 'A', itemvalue, 0 ) ) AS A,  
    sum( if( itemname = 'B', itemvalue, 0 ) ) AS B, 
    sum( if( itemname = 'C', itemvalue, 0 ) ) AS C 
FROM 
    bob 
GROUP BY 
    hostid;
于 2009-08-10T13:12:13.937 回答
47

另一个选项,如果您有许多需要旋转的项目特别有用,是让 mysql 为您构建查询:

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, ' 
                  FROM history 
                   GROUP BY hostid');

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

FIDDLE 添加了一些额外的值以查看它的工作原理

GROUP_CONCAT默认值为 1000,因此如果您有一个非常大的查询,请在运行之前更改此参数

SET SESSION group_concat_max_len = 1000000;

测试:

DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);

INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);

  hostid    A     B     C      D
    1     10      3     0      0
    2     9       0    40      5
    3     14     67     0      8
于 2015-02-02T19:13:09.277 回答
28

利用 Matt Fenwick 帮助我解决问题的想法(非常感谢),让我们将其简化为一个查询:

select
    history.*,
    coalesce(sum(case when itemname = "A" then itemvalue end), 0) as A,
    coalesce(sum(case when itemname = "B" then itemvalue end), 0) as B,
    coalesce(sum(case when itemname = "C" then itemvalue end), 0) as C
from history
group by hostid
于 2012-10-22T07:07:50.270 回答
17

我从子查询中编辑Agung Sagita的答案以加入。我不确定这两种方式之间有多大区别,但仅供参考。

SELECT  hostid, T2.VALUE AS A, T3.VALUE AS B, T4.VALUE AS C
FROM TableTest AS T1
LEFT JOIN TableTest T2 ON T2.hostid=T1.hostid AND T2.ITEMNAME='A'
LEFT JOIN TableTest T3 ON T3.hostid=T1.hostid AND T3.ITEMNAME='B'
LEFT JOIN TableTest T4 ON T4.hostid=T1.hostid AND T4.ITEMNAME='C'
于 2012-12-19T07:22:31.527 回答
13

使用子查询

SELECT  hostid, 
    (SELECT VALUE FROM TableTest WHERE ITEMNAME='A' AND hostid = t1.hostid) AS A,
    (SELECT VALUE FROM TableTest WHERE ITEMNAME='B' AND hostid = t1.hostid) AS B,
    (SELECT VALUE FROM TableTest WHERE ITEMNAME='C' AND hostid = t1.hostid) AS C
FROM TableTest AS T1
GROUP BY hostid

但是如果子查询产生多于一行,这将是一个问题,在子查询中使用进一步的聚合函数

于 2011-11-02T06:00:53.437 回答
7

如果您可以使用MariaDB,那么有一个非常简单的解决方案。

MariaDB-10.02开始,添加了一个名为CONNECT的新存储引擎,它可以帮助我们将另一个查询或表的结果转换为数据透视表,就像您想要的一样:您可以查看文档

首先安装连接存储引擎

现在我们表itemname的数据透视表是,每个项目的数据都位于itemvalue列中,因此我们可以使用以下查询获得结果数据透视表:

create table pivot_table
engine=connect table_type=pivot tabname=history
option_list='PivotCol=itemname,FncCol=itemvalue';

现在我们可以从中选择我们想要的pivot_table

select * from pivot_table

更多细节在这里

于 2019-06-19T15:06:29.863 回答
5

我的解决方案:

select h.hostid, sum(ifnull(h.A,0)) as A, sum(ifnull(h.B,0)) as B, sum(ifnull(h.C,0)) as  C from (
select
hostid,
case when itemName = 'A' then itemvalue end as A,
case when itemName = 'B' then itemvalue end as B,
case when itemName = 'C' then itemvalue end as C
  from history 
) h group by hostid

它在提交的案例中产生预期的结果。

于 2014-01-29T21:06:37.287 回答
4

我将其设置为Group By hostId然后它将仅显示具有值的第一行,
例如:

A   B  C
1  10
2      3
于 2011-04-28T08:54:56.810 回答
4

我想出了一种方法,让我的报告使用简单的查询将行转换为几乎动态的列。您可以在此处在线查看和测试它。

查询的列数是固定的,但值是动态的并且基于行的值。你可以构建它所以,我使用一个查询来构建表头,另一个来查看值:

SELECT distinct concat('<th>',itemname,'</th>') as column_name_table_header FROM history order by 1;

SELECT
     hostid
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue else '' end) as col1
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue else '' end) as col2
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue else '' end) as col3
    ,(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue else '' end) as col4
FROM history order by 1;

你也可以总结一下:

SELECT
     hostid
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue end) as A
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue end) as B
    ,sum(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue end) as C
FROM history group by hostid order by 1;
+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 | NULL |
|      2 |    9 | NULL |   40 |
+--------+------+------+------+

RexTester的结果:

RexTester 的结果

http://rextester.com/ZSWKS28923

对于一个真实的使用示例,下面的这份报告以列的形式显示了船只/公共汽车的出发到达时间以及可视化时间表。您将在最后一列看到一个未使用的附加列,而不会混淆可视化: sistema venda de passans online e consumidor final e controle de frota - xsl tecnologia - xsl.com.br ** 在线售票和展示的票务系统

于 2017-06-28T13:14:47.487 回答
1

这不是您正在寻找的确切答案,但它是我在项目中需要的解决方案,希望这对某人有所帮助。这将列出以逗号分隔的 1 到 n 行项目。Group_Concat 使这在 MySQL 中成为可能。

select
cemetery.cemetery_id as "Cemetery_ID",
GROUP_CONCAT(distinct(names.name)) as "Cemetery_Name",
cemetery.latitude as Latitude,
cemetery.longitude as Longitude,
c.Contact_Info,
d.Direction_Type,
d.Directions

    from cemetery
    left join cemetery_names on cemetery.cemetery_id = cemetery_names.cemetery_id 
    left join names on cemetery_names.name_id = names.name_id 
    left join cemetery_contact on cemetery.cemetery_id = cemetery_contact.cemetery_id 

    left join 
    (
        select 
            cemetery_contact.cemetery_id as cID,
            group_concat(contacts.name, char(32), phone.number) as Contact_Info

                from cemetery_contact
                left join contacts on cemetery_contact.contact_id = contacts.contact_id 
                left join phone on cemetery_contact.contact_id = phone.contact_id 

            group by cID
    )
    as c on c.cID = cemetery.cemetery_id


    left join
    (
        select 
            cemetery_id as dID, 
            group_concat(direction_type.direction_type) as Direction_Type,
            group_concat(directions.value , char(13), char(9)) as Directions

                from directions
                left join direction_type on directions.type = direction_type.direction_type_id

            group by dID


    )
    as d on d.dID  = cemetery.cemetery_id

group by Cemetery_ID

该墓地有两个通用名称,因此名称列在由单个 id 但两个名称 id 连接的不同行中,查询生成类似

    CemeteryID Cemetery_Name Latitude
    1 Appleton,Sulpher Springs 35.4276242832293

于 2013-10-10T14:58:42.663 回答
0

您可以使用几个LEFT JOINs。请使用此代码

SELECT t.hostid,
       COALESCE(t1.itemvalue, 0) A,
       COALESCE(t2.itemvalue, 0) B,
       COALESCE(t3.itemvalue, 0) C 
FROM history t 
LEFT JOIN history t1 
    ON t1.hostid = t.hostid 
    AND t1.itemname = 'A' 
LEFT JOIN history t2 
    ON t2.hostid = t.hostid 
    AND t2.itemname = 'B' 
LEFT JOIN history t3 
    ON t3.hostid = t.hostid 
    AND t3.itemname = 'C' 
GROUP BY t.hostid
于 2022-02-02T03:25:03.363 回答
-4

我很抱歉这么说,也许我没有完全解决你的问题,但 PostgreSQL 比 MySQL 早 10 年,并且与 MySQL 相比非常先进,并且有很多方法可以轻松实现这一点。安装 PostgreSQL 并执行这个查询

CREATE EXTENSION tablefunc;

然后瞧!这里有大量的文档:PostgreSQL: Documentation: 9.1: tablefunc or this query

CREATE EXTENSION hstore;

然后再次瞧!PostgreSQL:文档:9.0:hstore

于 2019-05-21T21:54:31.437 回答