简体   繁体   中英

MSACCESS: SELECT “How many days ago” {can return: today, yesterday, 2 days ago, …}, field1, field2, fieldN FROM mytable

I have a table with a timestamp column, and want to perform a SELECT that returns this column in a friendly way that express how many days ago it occurred, like "Today", "Yesterday", "2 days ago", "3 days ago"...

I'm unable to process data on destination, so my query must return the final string.

I'm already using DateDiff("d",timestamp,Date()) to determine an integer that represents, but I need to transform to the corresponding string.

I already suceeded constructing a helper table like [ intDays (PK), strDays ] and inner joinning, but this way I need to pre-populate with all range of values needed. I'm looking for a more universal solution that follows a conditional logic to output the correct string, like: (pseudo-code)

If DateDifference = 0 Then return "Today"
If DateDifference = 1 Then return "Yesterday"
return DateDifference & " days ago"

You can use iif() :

select iif(DateDiff("d", timestamp, Date()) = 0, "Today",
           iif(DateDiff("d", timestamp, Date()) = 1, "Yesterday",
               DateDiff("d", timestamp, Date()) & " days ago"
              )
          )

Note: the last expression might need to be cstr(DateDiff("d", timestamp, Date())) & " days ago" . I'm not sure if MS Access does the conversion automatically or generates an error if one of the arguments is not a string.

This type of logic would often be done at the application level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM