簡體   English   中英

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

[英]Oracle group by date, month and year

我有以下查詢,以按天(例如20160101)顯示每個國家/地區組的計數。

如何修改以下查詢,以便可以按日期,月份和年份分組?

請注意,當前正在使用Oracle數據庫。

提前謝謝了。

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)

如果datefield是字符串,則只需使用substr() 對於年份和月份:

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);

如果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');

使用專用功能會很聰明。 使用字符串可以奏效,但是會變慢,並且還會假設您的日期/時間格式等問題。

Oracle具有TRUNC函數,該函數可將日期“舍入”為日,月等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM