2016-03-30 106 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功能,其中「向下取整」的日期的日,月等