动态数据透视表将行更改为列

时间:2016-03-16 06:08:49

标签: mysql

我有架构:
See SQL Fiddle with Demo


但我想制作动态的用户名列数... 我试过这个查询

SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT
        CONCAT(
            'sum(case when nama = ''', nama, ''' then count else 0 end) AS ',
            replace(nama,'','')
            )
        )INTO @sql
 from (SELECT 
DATE_FORMAT(a.datetime,"%m-%Y") as bulan,
b.nm_user as nama, 
count(a.kd_user) as count
FROM tbl_log_login a, tbl_user b  where a.kd_user=b.id 
group by a.kd_user, DATE_FORMAT(a.datetime,"%m-%Y") order by a.datetime) c;

SET @sql = CONCAT('SELECT bulan, ',@sql, ' from (SELECT 
DATE_FORMAT(a.datetime,"%m-%Y") as bulan,
b.nm_user as nama, 
count(a.kd_user) as count
FROM tbl_log_login a, tbl_user b  where a.kd_user=b.id 
group by a.kd_user, DATE_FORMAT(a.datetime,"%m-%Y") order by a.datetime) c 
group by bulan');

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


但没什么看法,可能这个查询是假的..帮助,谢谢..

1 个答案:

答案 0 :(得分:0)

试试这个:

SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT
        CONCAT(
            'sum(case when nama = ''', nama, ''' then count else 0 end) AS ',
            replace(nama,' ','_')
            )
        )INTO @sql
 from (SELECT 
DATE_FORMAT(a.datetime,"%m-%Y") as bulan,
b.nm_user as nama, 
count(a.kd_user) as count
FROM tbl_log_login a, tbl_user b  where a.kd_user=b.id 
group by a.kd_user, DATE_FORMAT(a.datetime,"%m-%Y") order by a.datetime) c;

SET @sql = CONCAT('SELECT bulan, ',@sql, ' from (SELECT 
DATE_FORMAT(a.datetime,"%m-%Y") as bulan,
b.nm_user as nama, 
count(a.kd_user) as count
FROM tbl_log_login a, tbl_user b  where a.kd_user=b.id 
group by a.kd_user, DATE_FORMAT(a.datetime,"%m-%Y") order by a.datetime) c 
group by bulan');

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

注意:列别名中有空格。列别名中的空格不会起作用,除非它被引号括起来。在这种情况下,我用下划线替换了空格。

修改

SELECT @sql;

我得到了这个结果:

SELECT bulan, sum(case when nama = 'Reza' then count else 0 end) AS Reza,sum(case when nama = 'Super User' then count else 0 end) AS Super_User from (SELECT 
DATE_FORMAT(a.datetime,"%m-%Y") as bulan,
b.nm_user as nama, 
count(a.kd_user) as count
FROM tbl_log_login a, tbl_user b  where a.kd_user=b.id 
group by a.kd_user, DATE_FORMAT(a.datetime,"%m-%Y") order by a.datetime) c 
group by bulan;

单独执行此查询后,我得到以下结果:

bulan       Reza        Super_User
01-2016     1             1
02-2016     0             2
03-2016     0             2

<强>快照:

enter image description here