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

そして、次のような出力が必要です。年、月の結果カウントに基づいてレコードをカウントし、各行のデータも表示する必要があります。

私の場合:

  • 年: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

このようなデータを表示する必要があります。サイトのブログアーカイブセクションを参照してください。

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これは、次の2つの集計クエリを使用して取得できます。

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 に答える