我有一张桌子,用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 days
或3 months
或5 months 15 days
或9 days
我已经在SO上检查了年龄计算问题,但还有更复杂的问题。
答案 0 :(得分: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 '
答案 1 :(得分:-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