0

这是我想要做的一个例子:

我必须按月/年组织一个事件列表,其中包含事件计数,然后是这些事件 ID 的逗号列表。

这是我所拥有的:

     SELECT count(*) as counter, 
                   MONTHNAME(publishDate) as month, 
                   YEAR(publishDate) as year 
              FROM bursch.events 
     GROUP BY YEAR(publishDate), 
              MONTH(publishDate) 
     order by year desc;

但是,此外,我也需要这些 ID (2,5,6) <<< 像这样:

这是概念:

SELECT count(*) as counter, 
       MONTHNAME(publishDate) as month, 
       YEAR(publishDate) as year,
       (select id 
          from events 
          where 'call conditions affect the main query') as IDList 
              FROM events 
     GROUP BY YEAR(publishDate), 
              MONTH(publishDate) 
     order by year desc;

这将导致这样的事情:

counter  |  month   | year  | ids
-----------------------------------------
3        |  June    | 2013  | 45,49,50
4        |  July    | 2013  | 39,40,41,42
2        |  March   | 2011  | 33,34
5        |  May     | 2011  | 27,29,30,31,32
1        |  June    | 2011  | 22
4        |  July    | 2011  | 14,17,18,19
1        |  January | 2010  | 13

如果我可以将我的选择结果基于主选择语句的条件,那就太好了。可能有更好的方法来获得这个结果。也许是更简单的方法。但是选择作为字段部分。那会叫什么?相关查询?没有把握。我已经看到我可以在 Oracle 和 MySQL 中做到这一点并且它派上用场(如果我只知道它叫什么)。

先谢谢了。如果有不清楚的地方,请告诉我。

4

1 回答 1

2

MySQL 有一个名为GROUP_CONCAT()的函数,它连接行而不是列。

SELECT COUNT(*) as counter, 
       MONTHNAME(publishDate) as month, 
       YEAR(publishDate) as year,
       GROUP_CONCAT(id) as IDs
FROM   events 
GROUP  BY YEAR(publishDate), 
          MONTH(publishDate) 
ORDER  BY year desc;
于 2013-08-06T15:18:13.180 回答