MySQL单表静态和动态数据透视


8

我有一个看起来像这样的表:

+----------------------------------------+
|Name                | kode      | jum   |
+----------------------------------------+
| aman               |kode1      | 2     |
| aman               |kode2      | 1     |
| jhon               |kode1      | 4     |
| amir               |kode2      | 4     |
+--------------------+-----------+-------+

如何使用MySQL进行这样的视图?

                    kode1    kode2     count
aman                  2         1        3  
jhon                  0         4        4
amir                  0         4        4

Answers:


7

这是“枢轴”的一种形式,您应该使用该搜索词查找其他选项。

您可以尝试如下操作:

select
     name
   , sum(case when kode = 'kode1' then jum else 0 end) as 'kode1'
   , sum(case when kode = 'kode2' then jum else 0 end) as 'kode2'
   , sum(jum) as count
from foo
group by name;

(假设您的示例视图有的错误jhon

例:

mysql> select * from foo;
+------+-------+------+
| name | kode  | jum  |
+------+-------+------+
| aman | kode1 |    2 |
| aman | kode2 |    1 |
| jhon | kode1 |    4 |
| amir | kode2 |    4 |
+------+-------+------+
4 rows in set (0.00 sec)


mysql> select
    ->      name
    ->    , sum(case when kode = 'kode1' then jum else 0 end) as 'kode1'
    ->    , sum(case when kode = 'kode2' then jum else 0 end) as 'kode2'
    ->    , sum(jum) as count
    -> from foo
    -> group by name;
+------+-------+-------+-------+
| name | kode1 | kode2 | count |
+------+-------+-------+-------+
| aman |     2 |     1 |     3 |
| amir |     0 |     4 |     4 |
| jhon |     4 |     0 |     4 |
+------+-------+-------+-------+
3 rows in set (0.00 sec)

11

如果您知道已知的列数,则可以使用类似于其他答案的静态版本。但是,如果您有一个未知数,则可以使用类似于以下内容的准备好的语句

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when kode = ''',
      kode,
      ''' then jum else 0 end) AS ',
      kode
    )
  ) INTO @sql
FROM yourtable;


SET @sql = CONCAT('SELECT name, ', @sql, ', sum(jum) as `count`
                  FROM yourtable 
                  GROUP BY name');

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

参见带有演示的SQL Fiddle

结果是一样的:

| NAME | KODE1 | KODE2 | COUNT |
--------------------------------
| aman |     2 |     1 |     3 |
| amir |     0 |     4 |     4 |
| jhon |     4 |     0 |     4 |

8

要将行转换为列,您需要使用CASE语句。要获得个人的计数,kode您需要使用以下SUM函数:

SELECT NAME,
       SUM(CASE kode WHEN 'kode1' THEN jum ELSE 0 END) AS kode1
      ,SUM(CASE kode WHEN 'kode2' THEN jum ELSE 0 END) AS kode2
      ,SUM(jum) AS `Count`
FROM Table1
GROUP BY Name

看到这个SQLFiddle

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.