mysql,transpose / pivot row to column,变量选择

时间:2013-01-31 06:24:12

标签: mysql variables pivot transpose

再次问好,并提前感谢您的帮助。

我已经检查过几个先前的问题,但是找不到这个确切的情况。

我正在尝试将行转置/转移到列,但结果基于where子句中的日期函数,使我的选择有些变化。

SELECT
DATE_FORMAT(packet_details.installDate,'%m-%d-%Y') as Install_Date,
Count(packet_details.installDate)
FROM
packet_details
WHERE
 packet_details.installDate >= CURRENT_DATE - INTERVAL 7 DAY
 AND packet_details.installDate "*lessthan*" CURRENT_DATE + INTERVAL 7 DAY
GROUP BY installDate
*lessthan symbol wont show here on Stack & i don't know how to fix it

不确定这是否合理所以我包含了一个小提琴:http://sqlfiddle.com/#!2/5b235/3/0 所以像这样:

INSTALL_DATE     COUNT
1/24/2013         2
1/25/2013         2
1/26/2013         2
1/27/2013         2
1/28/2013         2
1/29/2013         1
2/3/2013          1
2/4/2013          1
2/5/2013          5
2/6/2013          4

变成:

INSTALL_DATE    1/24/2013   1/25/2013   1/26/2013   1/27/2013   1/28/2013....   
COUNT             2             2          2             2         2               1     

1 个答案:

答案 0 :(得分:1)

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;