我需要逐月获取数据并进行排序,为此我尝试了以下查询
select to_char(regn_date,'Mon-yyyy') "Month", count(id) "No of Persons"
from Person
group by to_char(regn_date,'Mon-yyyy')
order by to_char(regn_date,'Mon-yyyy')
我得到的输出是
月人数
Dec-2011 1383
Feb-2012 1230
Jan-2012 1409
Mar-2012 1495
Nov-2011 985
Oct-2011 825
Sep-2011 742
对字符串值进行升序排序,即按to_char排序(regn_date,' Mon-yyyy')asc
select to_char(regn_date,'Mon-yyyy') "Month", count(id) "No of Persons"
from Person
group by to_char(regn_date,'Mon-yyyy')
order by to_char(regn_date,'Mon-yyyy') asc
月人数
Dec-2011 1383
Feb-2012 1230
Jan-2012 1409
Mar-2012 1495
Nov-2011 985
Oct-2011 825
Sep-2011 742
获取数据排序结果会以不同的日期格式显示
select to_date(to_char(regn_date,'MM-YYYY'),'MM-YYYY') "Month", count(id) "Number of Persons" from Person
where trunc(regn_date) < '31-MAR-2012'
group by to_date(to_char(regn_date,'MM-YYYY'),'MM-YYYY')
order by to_date(to_char(regn_date,'MM-YYYY'),'MM-YYYY')asc
结果:
月份人数
9/1/2011 742
10/1/2011 825
11/1/2011 985
12/1/2011 1383
1/1/2012 1409
2/1/2012 1230
3/1/2012 1495
所需的输出是按日期顺序排序的数据,以升序显示月份和年份。
月人数
Sep-2011 742
Oct-2011 825
Nov-2011 985
Dec-2011 1383
Jan-2012 1409
Feb-2012 1230
Mar-2012 1495
答案 0 :(得分:0)
使用TO_CHAR
进行显示,使用TO_DATE
进行操作。
SQL> WITH DATA AS(
2 SELECT 'Dec-2011' mnth, 1383 persons FROM dual UNION ALL
3 SELECT 'Feb-2012' , 1230 persons FROM dual UNION ALL
4 SELECT 'Jan-2012', 1409 persons FROM dual UNION ALL
5 SELECT 'Mar-2012', 1495 persons FROM dual UNION ALL
6 SELECT 'Nov-2011', 985 persons FROM dual UNION ALL
7 SELECT 'Oct-2011', 825 persons FROM dual UNION ALL
8 SELECT 'Sep-2011', 742 persons from dual
9 )
10 SELECT to_char(to_date(mnth,'Mon-YYYY'), 'Mon-YYYY') mnth, persons
11 FROM DATA
12 ORDER BY to_date(mnth,'Mon-YYYY')
13 /
MNTH PERSONS
-------- --------------------
Sep-2011 742
Oct-2011 825
Nov-2011 985
Dec-2011 1383
Jan-2012 1409
Feb-2012 1230
Mar-2012 1495
7 rows selected.
SQL>
编辑 WITH
子句是为了演示而构建示例表。在您的数据库中,您只需使用您的表名重命名DATA,然后执行select查询。
所以,你的最终查询看起来像,
SELECT to_char(to_date(regn_date,'Mon-YYYY'), 'Mon-YYYY') regn_date,
count(id) "No of Persons"
FROM person
GROUP BY to_date(regn_date,'Mon-YYYY')
ORDER BY to_date(regn_date,'Mon-YYYY')
/
考虑到,regn_date
是literal
的输入。
如果regn_date
是date
,那么,
SELECT to_char(regn_date,'Mon-YYYY') regn_date,
count(id) "No of Persons"
FROM person
GROUP BY to_char(regn_date,'Mon-YYYY')
ORDER BY regn_date
/
答案 1 :(得分:0)
按实际日期排序,不转换为字符串:
SELECT to_char(regn_date,'Mon-yyyy') "Month", count(id) "No of Persons"
FROM Person
GROUP BY to_char(regn_date,'Mon-yyyy')
ORDER BY regn_date
答案 2 :(得分:0)
按月截断日期然后将其转换为MON-YYYY格式完成了这项工作。
SELECT to_char(TRUNC(regn_date, 'mm'),'MON-YYYY','nls_date_language=american'),count(id) FROM Person
GROUP BY TRUNC(regn_date, 'mm')
order by TRUNC(regn_date, 'mm')
我得到所需的输出分类和分组。谢谢你的帮助。