mysql, transpose/pivot row to column, variable selects

后端 未结 1 1480
离开以前
离开以前 2021-01-16 14:25

Hello again and thank you in advance for your help.

I\'ve checked a few prior questions and couldn\'t find this exact situation.

I\'m trying to transpose/pi

1条回答
  •  时光说笑
    2021-01-16 14:52

    SELECT  Install_DATE,
            MAX(CASE WHEN Install_DATE = '01-24-2013' THEN totalCount END) `01-24-2013`,
            MAX(CASE WHEN Install_DATE = '01-25-2013' THEN totalCount END) `01-25-2013`,
            MAX(CASE WHEN Install_DATE = '01-26-2013' THEN totalCount END) `01-26-2013`,
            .......
    FROM
    (
      SELECT DATE_FORMAT(packet_details.installDate,'%m-%d-%Y') as Install_Date,
             Count(packet_details.installDate) totalCount
      FROM   packet_details
      WHERE  packet_details.installDate >= CURRENT_DATE - INTERVAL 7 DAY AND 
             packet_details.installDate   < CURRENT_DATE + INTERVAL 7 DAY
      GROUP  BY installDate
    ) s
    
    • SQLFiddle Demo

    For unknown number of Install_Date, a Dynamic Query is much preferred,

    SET @sql = NULL;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'MAX(CASE WHEN Install_DATE = ''',
          Install_Date,
          ''' then totalCount end) AS `', Install_Date, '`' )
      ) INTO @sql
    FROM 
    (
      SELECT DATE_FORMAT(packet_details.installDate,'%m-%d-%Y') as Install_Date,
             Count(packet_details.installDate) totalCount
      FROM   packet_details
      WHERE  packet_details.installDate >= CURRENT_DATE - INTERVAL 7 DAY AND 
             packet_details.installDate   < CURRENT_DATE + INTERVAL 7 DAY
      GROUP  BY installDate
    ) s;
    
    SET @sql = CONCAT('SELECT Install_DATE, ', @sql, ' 
                        FROM
                        (
                          SELECT DATE_FORMAT(packet_details.installDate,''%m-%d-%Y'') as Install_Date,
                                 Count(packet_details.installDate) totalCount
                          FROM   packet_details
                          WHERE  packet_details.installDate >= CURRENT_DATE - INTERVAL 7 DAY AND 
                                 packet_details.installDate   < CURRENT_DATE + INTERVAL 7 DAY
                          GROUP  BY installDate
                        ) s');
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    • SQLFiddle Demo

    0 讨论(0)
提交回复
热议问题