结合日,月和年,获得最高日期

时间:2012-12-21 04:42:56

标签: sql tsql sql-server-2008-r2

我正在开发一款游戏,我有一个名为punishment的表格,其中包含以下架构

CREATE TABLE Punishment
(
  PunishmentId int identity(1,1) not null , 
  PunishmentDay int , 
  PunishmentMonth int , 
  PunishmentYear int ,
  GameId int 
)

PunishmentDay,PunishmentMonth,PunishmentYear是可以为零或无效或任何数字的数字。

GameId可以在此表中重复,意味着我可以多次对同一场比赛进行惩罚。

现在我的问题是我必须得到用户受到最高惩罚的punishmentId

我尝试了以下方式,但无法获得最大记录..

SELECT PunishmentId, DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE()))))

   FROM Punishment

4 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER()而不是相关子查询来查找最大年/月/日。 ROW_NUMBER()允许您根据order by子句分配递增的行号。然后,您可以只选择rownumber = 1的行。尝试这样的事情:

SELECT * FROM
( SELECT PunishmentId,PunishmentDay,PunishmentMonth,PunishmentYear, DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE())))) TotalDays, ROW_NUMBER() OVER(PARTITION BY GameId ORDER BY PunishmentYear, PunishmentMonth, PunishmentDay DESC) RowNumber
FROM Punishment
WHERE GameId = @GameId 
) OrderedPunishment
WHERE RowNumber = 1

注意:我没有检查这个语法,并且我将语句基于你的语句(几乎忽略了你的嵌套dateadds,也许有更好的方法来做到这一点)。我也刚刚注意到你的第二个名字ConvictCases_G ......我没有看到那应该是惩罚。

答案 1 :(得分:0)

我已经通过遵循sql

解决了这个问题
SELECT PunishmentId,PunishmentDay,PunishmentMonth,PunishmentYear, DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE()))))

FROM Punishment

WHERE GameId=@GameId  and 
DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE())))) 
= (SELECT MAX(DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE())))))   FROM Punishment where GameId=@GameId)

但仍在等待是否有更好的解决方案..

答案 2 :(得分:0)

这应该有效

SELECT   TOP 1 PunishmentId
FROM    
(
SELECT  TOP 100 PERCENT
        PunishmentId ,
        SUM(PunishmentDay + PunishmentMonth*30 + PunishmentYear*360) AS MaxPunishment
FROM    @p
GROUP   BY  PunishmentId
ORDER   BY  SUM(PunishmentDay + PunishmentMonth*30 + PunishmentYear*360) DESC 
)
AS X

答案 3 :(得分:0)

你也可以使用:

SELECT TOP 1 WITH TIES 
    PunishmentId,PunishmentDay,PunishmentMonth,PunishmentYear, 
    DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE())))) AS PunishmentEndDate
FROM Punishment
WHERE GameId=@GameId
ORDER BY PunishmentEndDate DESC