2013-08-06 48 views
0

这里就是我试图做一个例子:与现场选择为选择statment(?这是什么所谓的)

我有按月/年举办活动的列表与事件的计数,然后是这些事件的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中实现这一点,并且它派上用场(如果我只知道它叫做什么的话)。

谢谢先进。让我知道,如果有什么不清楚。

回答

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; 
+0

有它!不错的工作... –