2012-12-21 62 views
0

我上一场比赛,我在那里有一个表称为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 
+0

因为处罚不是日期。这些都是数字....可能是你得到3天的惩罚,我会得到2年的惩罚..和惩罚开始日期也定义在游戏的后期阶段。 – rahularyansharma

+1

然后,最大组合将是'MAX(年* 10000 +月* 100 +日)' –

+0

为什么不将规则化所有处罚时间在几天?您可以使用30天的月份和365天的年份,而不会显着不准确。 –

回答

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 ......我没有看到那应该是惩罚。

+0

这是一个复制过去的错误。我也编辑了这个表名。那实际上是惩罚表。谢谢你的回答。我会尝试用rownumber。 – rahularyansharma

0

我已经通过以下SQL

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

FROM Punishment 

WHERE [email protected] 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 [email protected]) 

,但仍然在等待,如果有任何更好的解决方案可以解决这个完成..

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 
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 [email protected] 
ORDER BY PunishmentEndDate DESC