【问题标题】:calculate duration in years months and days for each row计算每一行的年月和日持续时间
【发布时间】:2013-03-04 05:45:07
【问题描述】:

我有一张表,我在其中存储了玩家进入任何游戏的日期gameId and UserId

现在我必须计算每个用户玩游戏以来的时间。

表结构如下

create table  GameUser

(
   UserId int identity(1,1) not null, 
   UserName nvarchar(500)

)

insert into GameUser SELECT 'rahul'
insert into GameUser SELECT 'yunus'
insert into GameUser SELECT 'nitin'


Create table GameEntry 
 (
    EntryId int identity(1,1) not null,
    GameId int , 
    UserId int , 
    EntryDate smalldatetime

 )


insert into GameEntry SELECT 1,1,'01/01/2009'
insert into GameEntry SELECT 1,2,'05/01/2009'
insert into GameEntry SELECT 1,3,'12/01/2009'
insert into GameEntry SELECT 2,1,'01/01/2010'
insert into GameEntry SELECT 2,3,'01/01/2013'

SQL FIDDELE with table scheme and test data

我的持续时间结果列应该是这样的2 years 2 months and 15 days3 months5 months 15 days9 days

我已经在 SO 上检查了年龄计算问题,但还有更复杂的。

【问题讨论】:

  • 使用datediff(day, EntryDate, getdate()) 获取天数差异。之后,您只需要进行计算和格式化。
  • 当我手动计算时,30 天或 31 天或 28 天呢?因为我的出生日期是 1986 年 1 月 1 日,所以我今天 27 岁 2 个月零 3 天。 easycalculation.com/date-day/age-calculator.php谢谢
  • @rahularyansharma:上面的链接有两种情况:1.今天的日期:27/3/2013 & DOB:28/2/2013。答案是:0 年 0 个月 30 天。 2.今天日期:27/3/2013 & DOB:28/2/2012。答案是:1年0个月30天。在闰年的额外一天计算失败。你希望它是同样的方式吗?
  • 不,我不想要那个,我想计算确切的年月日。

标签: sql sql-server sql-server-2008 date


【解决方案1】:

你可以这样做:

Declare @DOB DateTime
DECLARE @yy INT
DECLARE @mm INT
DECLARE @getdd INT
DECLARE @dd INT

SET @DOB='2011-10-11 00:00:00.000'

SET @yy = DATEDIFF(mm, @DOB, GETDATE())/12
SET @mm = DATEDIFF(mm, @DOB, GETDATE())%12 - 1
SET @dd = ABS(DATEDIFF(dd, DATEADD(mm,@mm , DATEADD(yy, @yy, @DOB)), GETDATE()))

SELECT Convert(varchar(10),@yy) + ' Years ' + Convert(varchar(10),@mm) + ' Months '  + Convert(varchar(10),@dd) + ' Days '

【讨论】:

    【解决方案2】:

    你可以做这样的事情。将以年、月和日为单位返回日期。

    SELECT CAST(DATEDIFF(yyyy, Max(EntryDate), GETDATE()) AS VARCHAR) + ' years, ' 
         + CAST(DATEDIFF(mm, Max(EntryDate), GETDATE()) AS VARCHAR) + ' months, ' 
         + CAST(DATEDIFF(dd, Max(EntryDate), GETDATE()) AS VARCHAR) + ' days', 
         GE.userId
    FROM
        GameEntry AS GE
    GROUP BY
        GE.userId
    

    【讨论】:

    • 2 年 2 个月 15 天或 3 个月或 5 个月 15 天或 9 天,您在我的问题中检查了吗?
    • 哦,好吧...考虑到您的问题,我认为这就是您想要的。
    猜你喜欢
    • 2016-02-20
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2022-11-17
    • 2016-12-31
    相关资源
    最近更新 更多