分组并使行成为标题

时间:2014-11-19 04:32:11

标签: mysql

我在MySQL表fact

中有这些数据
+------------+-------+--------+
| timestamp  | code  | unique |
+------------+-------+--------+
| 1416157200 | 7E001 |    100 |
| 1416157200 | 7E002 |    200 |
| 1416243600 | 7E001 |    100 |
| 1416243600 | 7E002 |    200 |
+------------+-------+--------+

我想得到这个结果

+-------+------------+------------+
| code  | 2014-11-18 | 2014-11-17 |
+-------+------------+------------+
| 7E001 |        100 |        100 |
| 7E002 |        200 |        200 |
+-------+------------+------------+

我使用此查询select code, from_unixtime(timestamp, '%Y-%m-%d') as date, unique from fact;来生成此结果,并且无意将此结果聚合到上面的预期结果。

+-------+------------+--------+
| code  |    date    | unique |
+-------+------------+--------+
| 7E001 | 2014-11-17 |    100 |
| 7E002 | 2014-11-17 |    200 |
| 7E001 | 2014-11-18 |    100 |
| 7E002 | 2014-11-18 |    200 |
+-------+------------+--------+

有可能吗?以及如何实现这一目标? PS:请帮我编辑标题更具描述性,因为我无法在如此短的时间内解释这个问题

2 个答案:

答案 0 :(得分:0)

可以使用基于案例的聚合

由于日期可能很多,您需要使用动态SQL

  select code, 
      Max( case when  date=1416157200 then unique end) as '2014-11-17' ,
      Max( case when date=1416243600  t hen unique end) as '2014-11-18'
  from fact
  Group by date 

答案 1 :(得分:0)

是的,可以使用该值作为列创建动态查询。 我使用文章中的一些代码来描述获取pivot table in MySQL的方法:

mysql> call get_fact_pivot_table();
+-------+------------+------------+
| code  | 2014-11-16 | 2014-11-17 |
+-------+------------+------------+
| 7E001 |        100 |        100 |
| 7E002 |        200 |        200 |
+-------+------------+------------+
2 rows in set (0,06 sec)

过程get_fact_pivot_table包含一个用于进行动态查询的游标,您可以根据需要进行更改:

DELIMITER $$
DROP PROCEDURE if exists get_fact_pivot_table$$

CREATE PROCEDURE `get_fact_pivot_table`()
BEGIN

DECLARE done INT DEFAULT 0;
DECLARE p_sql text;
DECLARE p_col_date VARCHAR(20);
DECLARE p_col_value int;

DECLARE c_columns cursor FOR
    select distinct from_unixtime(timestamp, '%Y-%m-%d') as `col_date` , 
        `timestamp` as col_value
    from fact;

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

SET p_sql = 'select f.code ';
OPEN c_columns;

read_loop: LOOP
    FETCH c_columns INTO p_col_date, p_col_value;
    IF done THEN
      LEAVE read_loop;
    END IF;
    SET p_sql = concat(p_sql,
      ', (select c.`unique` from fact as c where 
      c.`timestamp` =  ', p_col_value ,' 
      and c.code = f.code limit 1) as `',p_col_date,'` ');

END LOOP;

SET @SQL = concat(p_sql,' from fact as f group by f.code');


close c_columns;

PREPARE stmt1 FROM @SQL;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1; 


END$$
delimiter ;