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条记录
  • Month:12 in 2011 有 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

我需要显示这样的数据,请参阅网站的博客存档部分

4

2 回答 2

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)
于 2012-12-06T13:06:10.660 回答
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)
于 2012-12-06T16:31:30.977 回答