I am working on a game , where i have a table called punishment
which have following schema
CREATE TABLE Punishment
(
PunishmentId int identity(1,1) not null ,
PunishmentDay int ,
PunishmentMonth int ,
PunishmentYear int ,
GameId int
)
PunishmentDay ,PunishmentMonth ,PunishmentYear are numbers which can be either zero or null or any number.
GameId
can be repeat in this table , means i can get multiple times punishment for the same game.
Now my question is i have to get the punishmentId
in which user get the highest punishment.
I have tried following way but not able to get the max record ..
SELECT PunishmentId, DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE()))))
FROM Punishment
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.
I have solved this by following 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)
but still waiting if there any better solution can be done ..
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.