3

可能重复:
MySQL 数据透视表

我应该使用派生表的左联接、使用派生表右联接、不同的表设计,还是需要查询表并编写 Python 代码以产生如下所示的所需输出?

我想得到的输出将产生以下输出示例:

==========================
| 2005   |  2006 |  2007 |  <--- These headings are not necessary
==========================
|   A    |  A    |  A    |
--------------------------
|  AA    |  AA   |  AA   |
--------------------------
|  BB    |  BB   |       |
--------------------------
|  C     |       |   C   |
--------------------------

查询的数据位于包含(符号,年份)的两列表中:

====================
|  Symbol |  Year  |
====================
|   A     |  2005  |
--------------------
|   AA    |  2005  |
--------------------
|   BB    |  2005  |
--------------------
|   C     |  2005  |
--------------------
|   A     |  2006  |
--------------------
|   AA    |  2006  |
--------------------
|   BB    |  2006  |
--------------------
|   A     |  2007  |
--------------------
|   AA    |  2007  |
--------------------
|   C     |  2007  |
--------------------
4

1 回答 1

5
SELECT MAX(CASE WHEN year = 2005 THEN Symbol ELSE NULL END) `2005`,
       MAX(CASE WHEN year = 2006 THEN Symbol ELSE NULL END) `2006`,
       MAX(CASE WHEN year = 2007 THEN Symbol ELSE NULL END) `2007`
FROM tableName
GROUP BY Symbol

如果您有未知的年份值,则非常喜欢动态 SQL 查询。

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN year = ',
      year,
      ' THEN Symbol ELSE NULL end) AS ',
      CONCAT('`', year, '`')
    )
  ) INTO @sql
FROM TableName;

SET @sql = CONCAT('SELECT  ', @sql, ' 
                   FROM tableName 
                   GROUP BY Symbol');

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

如果你想显示空字符串而不是null值,COALESCE是必需的。

于 2012-12-24T04:13:53.063 回答