[英]Get the highest date with combination of day,month and year
我正在開發一個游戲,其中有一個名為punishment
表,具有以下模式
CREATE TABLE Punishment
(
PunishmentId int identity(1,1) not null ,
PunishmentDay int ,
PunishmentMonth int ,
PunishmentYear int ,
GameId int
)
PunishmentDay,PunishmentMonth,PunishmentYear是可以為零或為null或任何數字的數字。
GameId
可以在此表中重復,這意味着我可以對同一游戲進行多次懲罰。
現在我的問題是我必須獲得其中punishmentId
最高的刑罰ID。
我嘗試了以下方法,但無法獲得最大記錄..
SELECT PunishmentId, DATEADD(DD,PunishmentDay,DATEADD(MM,PunishmentMonth,(DATEADD(YY,PunishmentYear,GETDATE()))))
FROM Punishment
您可以使用ROW_NUMBER()而不是相關子查詢來查找最大年/月/日。 ROW_NUMBER()將允許您基於order by子句分配遞增的行號。 然后,您只能選擇該行號= 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 ...我沒有看到那應該是懲罰。
我已經解決以下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)
但仍在等待是否有更好的解決方案可以..
這應該工作
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
您還可以使用:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.