简体   繁体   English

Oracle按日期,月份和年份分组

[英]Oracle group by date, month and year

I have the below query to show me the count for each country group by single days such as 20160101. 我有以下查询,以按天(例如20160101)显示每个国家/地区组的计数。

How can I modify the below query so it can group by date, month and year? 如何修改以下查询,以便可以按日期,月份和年份分组?

Please note currently working on an Oracle database. 请注意,当前正在使用Oracle数据库。

Many Thanks in advance. 提前谢谢了。

Select count(1), country_of_sale, substr(datefield,1,8) AS datefield1
from table 
where country_of_sale IN (‘USA’,’EUROPE’,’ASIA’)
group by country_of_sale, substr(datefield,1,8)
order by substr(datefield,1,8)

If datefield is a string, then just use substr() . 如果datefield是字符串,则只需使用substr() For year and month: 对于年份和月份:

Select count(1), country_of_sale, substr(datefield, 1, 6) AS yyyymm
from table 
where country_of_sale IN ('USA', 'EUROPE', 'ASIA')
group by country_of_sale, substr(datefield, 1, 6)
order by substr(datefield, 1, 6);

If datefield is a date, then use to_char() : 如果datefield是一个日期,则使用to_char()

Select count(1), country_of_sale, to_char(datefield, 'YYYY-MM') AS yyyymm
from table 
where country_of_sale IN ('USA', 'EUROPE', 'ASIA')
group by country_of_sale, to_char(datefield, 'YYYY-MM')
order by to_char(datefield, 'YYYY-MM');

It would be smart to use dedicated functionality. 使用专用功能会很聪明。 Playing with strings will work, but can be slower and it also assumes things about your date/time formatting etc. 使用字符串可以奏效,但是会变慢,并且还会假设您的日期/时间格式等问题。

Oracle has a TRUNC function, which "rounds down" a date to a day, month, etc. Oracle具有TRUNC函数,该函数可将日期“舍入”为日,月等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM