如何在数据透视表中对concat和sum(不可预测)值进行分组?

时间:2014-06-04 23:25:30

标签: mysql sql

我得到了一个数据透视表(请注意,键是已知的,但不是每个键都存储的值,例如日期):

      ID              Reference          Key               Value
    -------------------------------------------------------------
    01                  001             date                03/04/2009
    02                  001             shift               1st
    03                  001             station a           Mark
    04                  001             station b           John
    05                  001             station b           Macy
    06                  002             date                04/04/2009
    07                  002             shift               2nd
    08                  002             station a           John
    09                  002             Station a           Drey
    10                  002             Station b           Macy

我想拥有:

    Operator         Dates             1st Shift    2nd shift   A Station  B Station
    ---------+-----------------------+------------+------------+----------+--------
    Mark      03/04/2009                   2              0           1        0
    John      03/04/2009, 04/04/2013       1              1           1        1
    Macy      03/04/2009, 04/04/2009       1              1           0        2
    Drey      04/04/2009                   0              1           1        0

换句话说:"日期"专栏显示每个雇员工作的日子。其他列计算每个员工在每个站点和每个班次工作的次数。

如果查询适合视图,也会很棒....

很多! 也许它可能与以下内容有关:

    SET @sql = NULL; 
    SELECT GROUP_CONCAT(DISTINCT CONCAT( 'SUM(IF(tblColumn = ''', tblColumn, ''', 1, 0)) AS ', tblColumn ) ) 
    INTO @sql FROM Table1; SET @sql = CONCAT('SELECT ', @sql, ' FROM Table1'); 
    PREPARE stmt 
    FROM @sql; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt;

1 个答案:

答案 0 :(得分:0)

我认为这会做你想做的事情:

select name, group_concat(d.value separator ', ') as dates,
       sum(s.value = '1st') as FirstShift,
       sum(s.value = '2nd') as SecondShift,
       sum(n.key = 'station a') as StationA,
       sum(n.key = 'station b') as StationB
from (select value as name, key, reference
      from table t
      where key in ('station a', 'station b')
     ) n join
     table d
     on n.reference = d.reference and d.key = 'date' join
     table s
     on n.reference = s.reference and s.key = 'shift'
group by name;