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
4

4 回答 4

1

You can use ROW_NUMBER() instead of a correlated subquery to find the max year/month/day. ROW_NUMBER() will allow you assign an incrementing row number based on an order by clause. You can then select only rows where that rownumber = 1. Try something like this:

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

Note: I haven't checked this for syntax, and I based the statement off your statement (pretty much ignored your nested dateadds, maybe there is a better way to do that too). I also only just now noticed your second table name ConvictCases_G... I didn't see that that is supposed to be Punishment.

于 2012-12-21T08:21:49.577 回答
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)

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

于 2012-12-21T04:59:37.993 回答
0

This should work

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
于 2012-12-21T08:29:42.117 回答
0

You could also use:

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
于 2012-12-22T07:28:13.980 回答