sql >> Database teknologi >  >> RDS >> Mysql

mysql, transponer/pivot række til kolonne, variabelvalg

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

For ukendt antal Install_Date , en dynamisk forespørgsel er meget foretrukket,

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;



  1. Ren måde at bruge postgresql vinduesfunktioner i django ORM?

  2. 8 Nye Oracle-kompatibilitetsfunktioner i EnterpriseDB PPAS 9.2 Beta

  3. MySQL sammenligne now() (kun dato, ikke tid) med et datetime-felt

  4. Kan PostgreSQL indeksere array-kolonner?