Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

Displaying data by only month and year in SQL (Oracle)

I have a set of data, I want to display the transactions per-month for the last 12 months grouped and ordered by month.

My Code is currently:

SELECT
to_char(orderdate, 'MM-YYYY') AS MONTH_AND_YEAR
,SUM(VALUE) AS TOTAL_SALES
,ROUND(AVG(VALUE),2) AS AVERAGE_SALE_VALUE
,MIN(VALUE) AS MINIMUM_SALE_VALUE
,MAX(VALUE) AS MAXIMUM_SALES_VALUE
FROM ORDER_TABLE
WHERE OrderDate >= ADD_MONTHS( TRUNC(SYSDATE), -12 )
GROUP BY to_char(orderdate, 'MM-YYYY')
ORDER BY to_char(orderdate, 'MM-YYYY') DESC;

but is returning :

MONTH_AND_YEAR

12-2021
12-2020
11-2021
11-2020
10-2021
10-2020
09-2021
09-2020
08-2021
08-2020
07-2020
06-2020
05-2021
05-2020
04-2021
04-2020
03-2021
03-2020
02-2020
01-2021
01-2020

helpful:

MAX(ORDERDATE) MIN(ORDERDATE)
2021-12-01 00:00:00 2020-01-02 00:00:00
question from:https://stackoverflow.com/questions/65943097/displaying-data-by-only-month-and-year-in-sql-oracle

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use:

ORDER BY MIN(orderdate) DESC;

Ordering by a string representation starting with the month is not going to produce the results you want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...