SQL Server将日期时间转换为n周期 [英] SQL Server Convert date time to n period ago

查看:624
本文介绍了SQL Server将日期时间转换为n周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字段 lastLogin ,它是datetime。
如果用户的最后一次登录时间是年龄的

,那么如果不到1年,而不是

n个月前,如果比前一天的

少1个月,如果不到那个1天比

n小时前,如果距离分钟前的

少于1小时,如果距离不到1分钟
n秒前

I have a field lastLogin which is datetime. I want to show the user his/her last login time as
n years ago, if it is less that 1 year than
n months ago, if it is less that 1 month than
n days ago, if it is less that 1 day than
n hours ago, if it is less that 1 hour than
n minutes ago, if it is less that 1 minutes than
n seconds ago

我希望 在几年,几个月,几天,微软和秒会自动作为英文语法规则处理。

I want that the s in years , months , days , hours , minures and seconds are handled automatically as the rules of English Grammar.

我是sql中的一个完整的初学者,我正在使用 SQL SERVER 2008 R2

i am a complete beginner in sql and i am using SQL SERVER 2008 R2

推荐答案

您可以使用 CASE 语句

CASE
    WHEN DATEDIFF(yy, lastLogin, GETDATE()) > 1 THEN CASE(DATEDIFF(yy, lastLogin, GETDATE()) AS varchar(5) + ' years ago'
    WHEN DATEDIFF(y, lastLogin, GETDATE()) = 1 THEN '1 year ago'
    -- ... and so on
END AS LastLoginPeriod

未测试和写入晚饭准备好了!

Not tested and written in a hurry as supper is ready!

这篇关于SQL Server将日期时间转换为n周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆