-1

我有一张表,我存储玩家进入任何游戏的日期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

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

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

4

2 回答 2

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 '
于 2013-03-06T07:00:33.343 回答
-1

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

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
于 2013-03-04T06:13:12.267 回答