2016-08-01 72 views
0

我有一組月度職位。我需要一個數組,其中包含每個月發佈的帖子的總記錄(包括零)。 我不把它寫在DQL :(任何想法PLZSymfony - doctrine2中的子查詢

樣本數據:

+----+---------------------+ 
| id | date    | 
+----+---------------------+ 
| 24 | 2012-12-16 16:29:56 | 
| 1 | 2013-02-25 14:57:09 | 
| 2 | 2013-02-25 14:59:37 | 
| 4 | 2013-02-25 15:12:44 | 
| 5 | 2013-02-25 15:14:18 | 
| 7 | 2013-02-26 11:31:31 | 
| 8 | 2013-02-26 11:31:59 | 
| 10 | 2013-02-26 11:34:47 | 
| 14 | 2013-03-04 04:39:02 | 
| 15 | 2013-03-04 05:44:44 | 
| 16 | 2013-03-04 05:48:29 | 
| 19 | 2013-03-07 15:22:34 | 
| 20 | 2013-03-15 12:24:43 | 
| 21 | 2013-03-16 16:27:43 | 
| 22 | 2013-03-16 16:29:28 | 
| 23 | 2013-03-16 16:29:56 | 
| 11 | 2013-03-17 11:35:12 | 
+----+---------------------+ 

SQL查詢:

SELECT count(b.id) as totalRec 
FROM (
      SELECT 'January' mnth 
      UNION ALL 
      SELECT 'February' mnth 
      UNION ALL 
      SELECT 'March' mnth 
     ) a 
     LEFT JOIN post b 
      ON a.mnth = DATE_FORMAT(b.date, '%M') AND 
       year(b.date) = '2013' AND 
       DATE_FORMAT(b.date, '%M') IN ('January', 'February', 'March') 
GROUP BY year(b.date)-month(b.date) 
ORDER BY b.date ASC 

輸出

+----------+ 
| totalRec | 
+----------+ 
|  0 | 
|  7 | 
|  9 | 
+----------+ 

回答

0

計數的所有分組帖子按月份篩選出您想要的月份:

SELECT count(*) as totalRec, DATE_FORMAT(b.date, '%m%Y') as month 
FROM post b 
WHERE month IN('012013', '022013', '032013') 
GROUP BY month 
ORDER BY b.date ASC 

會導致:

+----------+----------+ 
| totalRec | month | 
+----------+----------+ 
|  0 | 012013 | 
|  7 | 022013 | 
|  9 | 032013 | 
+----------+----------+ 
+0

THX的人,但如果沒有記錄 '012013' 的結果WIL + ---------- + ----- ----- + | totalRec |月| + ---------- + ---------- + | 7 | 022013 | | 9 | 032013 | + ---------- + ---------- + – ghazi2008

+0

是的,你是對的 – NDM

+0

你不知道我該怎麼做? – ghazi2008