Mysql
 sql >> база данни >  >> RDS >> Mysql

mysql, транспониране/завъртане на ред в колона, избор на променлива

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

За неизвестен брой Install_Date , Динамична заявка е много предпочитано,

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. C# параметризирана заявка MySQL с клауза „in“.

  2. Използване на 'OR' между клаузата HAVING и WHERE в MySQL?

  3. Въведете моя php в mysql без повторение?

  4. MySQL:Как да разбера кои таблици препращат към конкретна таблица?

  5. ИЗБЕРЕТЕ ред по DATEPART()