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
168 views
in Technique[技术] by (71.8m points)

sql - Query to get the details for last 15 days from a PostgreSQL table

I have a pre-existing PostgreSQL table called "Students" and a column named "Date of joining" in it along with other columns. Datatype of "Date of joining" column is varchar.

My requirement is to get the list of all students from the table who joined the class from last 15 days. I need to sort and get details from the table using "Date of joining" column. I'm not allowed to alter the datatype of the column to "date".

Table Sample

enter image description here

Desired output

enter image description here

I'm getting error while fetching the details since the column datatype is varchar.

Please help me to get the query for above scenario?

Thanks in Advance.

question from:https://stackoverflow.com/questions/66046522/query-to-get-the-details-for-last-15-days-from-a-postgresql-table

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

1 Reply

0 votes
by (71.8m points)

We cannot say how to solve this completely. But you can convert your column into a type date by using an appropriate date pattern. In this example the dates could like this: 2020-01-15. So the pattern to convert this into a date would be year-month-day which is YYYY-MM-DD. Any other pattern is possible.

SELECT
    *
FROM mytable
WHERE to_date(date_of_joining, 'YYYY-MM-DD') 
    BETWEEN CURRENT_DATE AND CURRENT_DATE - interval '15 days'

EDIT (user added sample data):

demo:db<>fiddle

In your case the date pattern would be: 'DD-Mon-YY'


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

...