如何组合这些由同一字段分组的查询?

时间:2012-10-26 02:51:15

标签: mysql sql

我有以下三个查询

SELECT COUNT(*) as cached_type_a, DATE(datetime) as datetime
    FROM requests
    WHERE cached = 'a'
    GROUP BY DAY(datetime);

SELECT COUNT(*) as cached_type_b, DATE(datetime) as datetime
    FROM requests
    WHERE cached = 'b'
    GROUP BY DAY(datetime);

SELECT COUNT(*) as cached_type_c, DATE(datetime) as datetime
    FROM requests
    WHERE cached = 'c'
    GROUP BY DAY(datetime);

是否可以将它们组合成一个包含4列

的查询

cached_type_acached_type_bcached_type_cdatetime

2 个答案:

答案 0 :(得分:1)

如果cache只有三个可能的值,则可以使用此

SELECT DATE(datetime) as datetime,
        SUM(CASE WHEN cached = 'a' THEN 1 ELSE 0 END) cached_a,
        SUM(CASE WHEN cached = 'b' THEN 1 ELSE 0 END) cached_b,
        SUM(CASE WHEN cached = 'c' THEN 1 ELSE 0 END) cached_c
FROM requests
GROUP BY DAY(datetime)

否则,如果您有多个缓存,则可以使用Prepared Statement

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN cached =  ''',
      cached,
      ''' then 1 ELSE 0 end) AS ',
      CONCAT('cached_',cached)
    )
  ) INTO @sql
FROM requests;

SET @sql = CONCAT('SELECT DATE(datetime) as datetime, ', @sql, ' 
                   FROM requests 
                   GROUP BY DAY(datetime)');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

答案 1 :(得分:0)

 SELECT COUNT(a.datetime) as cached_type_a,
        COUNT(b.datetime) as cached_type_b,
        COUNT(c.datetime) as cached_type_c,
        DATE(a.datetime) as datetime
 FROM requests a, 
      requests b,
      requests c,  
 WHERE a.cached = 'a' 
   and b.cached = 'b'
   and c.cached = 'c'
 GROUP BY DAY(a.datetime), DAY(b.datetime), DAY(c.datetime);