0

私は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、どのユーザーが最高の罰を受けるかを取得する必要があるということです。

次の方法を試しましたが、最大レコードを取得できません..

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

   FROM Punishment
4

4 に答える 4

1

相関サブクエリの代わりに 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をほとんど無視しました。おそらくそれを行うより良い方法もあります)。また、あなたの 2 番目のテーブル名 ConvictCases_G に気付いたのはつい最近のことです...それが罰であるはずだとは思いませんでした。

于 2012-12-21T08:21:49.577 に答える
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
于 2012-12-22T07:28:13.980 に答える
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

これはうまくいくはずです

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 に答える