2012-12-06 108 views
0

我有這樣的數據表:我如何按月份和年份的數據計數

id | question | pub_date 
1 | qeustion1| 2012-12-03 
2 | qeustion2| 2012-12-06 
3 | qeustion3| 2012-11-03 
4 | qeustion4| 2011-12-03 

,我想的輸出,如:,月 應該算今年的基礎上記錄結果計數與Desc命令並應顯示每行數據。

在我的情況:

  • 年份:2012有3條記錄
  • 月份:2012年12年級有2條
  • 年份:2011有1個記錄
  • 月:在2011年12 1記錄。

我已經試過這樣:

SELECT 
    EXTRACT(MONTH FROM pub_date) as month, 
    EXTRACT(YEAR FROM pub_date) as year, 
    Count(id) 
FROM 
    mytable 
GROUP BY 
    month, 
    year 
ORDER BY 
    year DESC, 
    month DESC 

我需要顯示這樣的數據看Site

+0

基本上就是那樣的y你需要在你的PHP或其他代碼中使用兩個querys(一年一個月)。也許你可以顯示輸出你想從你的示例數據 – Justin

回答

1

我假設你想要的結果是一樣的東西:

2012   3 
2012 12  2 
2012 11  1 
2011   1 
2011 11  1 

您可以通過使用union在兩個聚合得到這個查詢:

select s.* 
from ((select year(pub_date) as yr, NULL as month, count(*) as cnt 
     from t 
     group by year(pub_date) 
    ) union all 
     (select year(pub_date) as yr, month(pub_date) as mon, count(*) as cnt 
     from t 
     group by year(pub_date), month(pub_date) 
    ) 
    ) s 
order by yr desc, 
     (case when mon is null then -1 else mon end) 
1

博客歸檔部分試試這個:

select count(id) 
from mytable 
group by year(pub_date), month(pub_date) 
order by year(pub_date) desc, month(pub_date) desc 

如果你想知道哪些月份和年份在哪裏,請使用:

select year(pub_date) as year, month(pub_date) as month, count(id), * 
from mytable 
group by year(pub_date), month(pub_date) 
order by year(pub_date) desc, month(pub_date) desc 

充分利用三個月的數據,也是多年

select year(pub_date) as year, year_count, month(pub_date) as month, count(rowid) as month_count 
from mytable u 
, (
select year(pub_date) as year, count(rowid) year_count 
from mytable 
group by year(pub_date) 
) as tab 
where tab.year = year(u.pub_date) 
group by year(pub_date), month(pub_date) 
+0

這將返回計數只有數據。 –

+0

在那裏,更新了查詢 –

+0

它的行爲與我的查詢完全相同。我也需要數據。你看到我提到的鏈接嗎? –