2016-03-30 109 views
0

组我有下面的查询,以显示我计数单的日子,如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) 
+0

请显示表格定义,样本表格数据和预期输出。 – OldProgrammer

+0

你的意思是你要求每个月的所有日期***和***每个月的小计***和***每年的小计?像'ROLLUP'一样?可以肯定的是,对您来说最好的选择是包含一些示例数据和您期望从示例数据中获得的结果。 – MatBailie

回答

1

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

这将是明智使用专用的功能。用绳子打会的工作,但速度可能很慢,它也假定你的日期/时间格式等东西

Oracle有一个TRUNC功能,其中“向下取整”的日期的日,月等