获取给定两个日期的天数、月数、年数并进行类型转换
我试图从 2 个日期获取天数、月份和年份,但这些都是单独的
DECLARE @datecount INT;
DECLARE @monthcount INT;
DECLARE @yearcount INT;
SELECT @datecount = (SELECT DATEDIFF(DAY, usr.registrationdate, GETDATE())
FROM users usr
WHERE usr.userid = @UserId);
SELECT @monthcount = (SELECT DATEDIFF(MONTH, usr.registrationdate, GETDATE())
FROM users usr
WHERE usr.userid = @UserId);
SELECT @yearcount = (SELECT DATEDIFF(YEAR, usr.registrationdate, GETDATE())
FROM users usr
WHERE usr.userid = @UserId);
如何投射这 3 个变量?或者我怎样才能一步获得这个?
no. of days / no. of months / no. of year
我想要的输出是 = 3:1:2
或 3 天/1 个月/4 年
I am trying to get the number of days,month and year from 2dates, but those are getting individual
DECLARE @datecount INT;
DECLARE @monthcount INT;
DECLARE @yearcount INT;
SELECT @datecount = (SELECT DATEDIFF(DAY, usr.registrationdate, GETDATE())
FROM users usr
WHERE usr.userid = @UserId);
SELECT @monthcount = (SELECT DATEDIFF(MONTH, usr.registrationdate, GETDATE())
FROM users usr
WHERE usr.userid = @UserId);
SELECT @yearcount = (SELECT DATEDIFF(YEAR, usr.registrationdate, GETDATE())
FROM users usr
WHERE usr.userid = @UserId);
How to cast these 3 variables? Or how can I get this in one step?
no. of days / no. of months / no. of year
What I want the output is = 3:1:2
or 3 days / 1 month / 4 years
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用户定义的函数对此很有用。
因为这样一个间隔的正确计算并不像人们想象的那么简单。
下面的 UDF 计算 2 个日期之间的间隔,并以 JSON 对象的格式输出。
在 db<>fiddle 此处
A user-defined function can be useful for this.
Since the correct calculation for such an interval isn't as straight forward as one would assume.
The UDF below calculates the interval between 2 dates, with the output in the format of a JSON object.
Test on db<>fiddle here