How can I sort by date in ms access 2007?

2019-06-05 00:26发布

问题:

Just want to know how do I sort a text column that shows data in date format mm/dd/yyyy.

回答1:

You will first have to convert to a date to get a proper sort. This is a query that converts Datetext to RealDate, and then sorts on that column (field). You can also click the header to choose the sort order.

SELECT 
   t.ID, 
   t.Datetext, 
   DateSerial(Mid([Datetext],InStrRev([Datetext],"/")+1),
              Mid([Datetext],1,InStr([Datetext],"/")-1),
              Mid([Datetext],InStr([Datetext],"/")+1,
                 (InStrRev(Datetext,"/")-InStr([Datetext],"/"))-1)) AS RealDate
FROM Table t
Order By 3

You can use IIf to avoid errors from null:

IIf([Datetext] Is Null,Null,DateSerial(
           Mid([Datetext],InStrRev([Datetext],"/")+1),
           Mid([Datetext],1,InStr([Datetext],"/")-1),
           Mid([Datetext],InStr([Datetext],"/")+1,
              (InStrRev(Datetext,"/")-InStr([Datetext],"/"))-1))) AS RealDate


回答2:

In a comment you said this is a "text column displaying date from a sql table". I'm unsure what you meant by that, but I think the situation could be simpler if you can convert the text column to an actual Date/Time column.

If you're importing data from SQL Server into Access, convert those text values when you pull them in to Access.

If the Access table is a link to a SQL Server object, create a view in SQL Server which casts the text date column to an Access-compatible date type. Then on the Access side, replace your existing link with a link to the view.

If you need to edit the date values in Access, not just display and sort them, include both the original text column and the transformed date version in your view. Do your Access edits to the text column; sort on the Date/Time column.