在Mysql

时间:2016-07-23 15:23:14

标签: mysql sql select group-by group-concat

我有两个表:table1table2,两个表的结构都是; id - day - uniques - pageviews。我想创建一个包含uniques格式的2387|1283值的附加字段,同时在给定日期汇总uniquespageviews。我有:

SELECT id, 
       day, 
       Sum(uniques)   AS uniques, 
       Sum(pageviews) AS pageviews 
FROM   (SELECT * 
        FROM   table1 
        WHERE ` day ` >= '2016-07-21' 
              AND ` day ` <= '2016-07-22' 
        UNION 
        SELECT * 
        FROM   table2 
        WHERE ` day ` >= '2016-07-21' 
              AND ` day ` <= '2016-07-22') t1 
GROUP  BY ` day ` 
ORDER  BY ` day ` ASC 

但是,对于2个表中的给定天数,这只是uniquespageviews的总和,但我还需要知道确切的值。假设table1中有5个,table2中有3个。此查询会返回一个“唯一”字样。值为8的字段。我还需要单独获取值5和3

任何帮助都会节省很多宝贵的时间;)

谢谢

1 个答案:

答案 0 :(得分:0)

您的查询请求总和。也许您可以执行GROUP_CONCAT(MySQL reference),以便该列返回由分隔符分隔的各个值。样本如下:

SELECT id, 
   day, 
   SUM(uniques)            AS uniques, 
   GROUP_CONCAT(CONCAT(uniques, ':', `tablename`) SEPARATOR '|')   AS uniques_values, 
   SUM(pageviews)          AS pageviews, 
   GROUP_CONCAT(CONCAT(pageviews, ':', `tablename`) SEPARATOR '|') AS pageviews_values 
FROM   (SELECT * , 'table1' as `tablename`
        FROM   table1 
        WHERE  day >= '2016-07-21' 
               AND day <= '2016-07-22' 
        UNION 
        SELECT * , 'table2' as `tablename`
        FROM   table2 
        WHERE  day >= '2016-07-21' 
               AND day <= '2016-07-22') t1 
GROUP  BY day 
ORDER  BY day ASC 

希望有所帮助:)