如何在SQL中获取最大子集的最大记录

时间:2018-09-13 20:43:25

标签: sql sql-server database

我有下表:

训练发生

Id   Training Id   Due Date
5    1             09/01/2018
6    1             09/15/2018
7    2             09/01/2018

培训发生用户

Id   Training Material Occurrence Id   User Id
1    5                                 'Chad'
2    5                                 'Chad'
3    6                                 'Chad'
4    6                                 'Chad'
5    7                                 'Chad'

我的查询需要获取最新培训材料发生表的最新培训材料发生用户记录。因此,如果我将用户“ Chad”传递给了

我想看看:

Id   Occurrence Id   User     Training Id   Due Date
4    6               'Chad'   1             09/15/2018
5    7               'Chad'   2             09/01/2018

这是我的查询:

SELECT tmou.*, tmo.TrainingMaterialId, tmo.DueDate
FROM dbo.TrainingMaterialOccurrenceUser as tmou
INNER JOIN dbo.TrainingMaterialOccurrence as tmo on
tmou.TrainingMaterialOccurrenceId = tmo.Id
AND tmou.Id IN (SELECT MAX(tmou.Id)
        FROM dbo.TrainingMaterialOccurrenceUser as tmou
        WHERE tmou.UserId = @UserId
        AND tmou.TrainingMaterialOccurrenceId IN (SELECT MAX(tmo.Id) as occurrenceId
                              FROM dbo.TrainingMaterialOccurrence as tmo
                               WHERE tmo.Id IN (Select TrainingMaterialOccurrenceId FROM dbo.TrainingMaterialOccurrenceUser as tmou1 WHERE tmou1.UserId = @UserId)
                            GROUP BY tmo.TrainingMaterialId)
        GROUP BY tmou.TrainingMaterialOccurrenceId)

如您所见,这是一团糟。关于如何清除此问题的任何想法。

1 个答案:

答案 0 :(得分:1)

// Website you wish to allow to connect res.header('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.header('Access-Control-Allow-Headers', 'Accept, Content-Type, X-Requested-With', 'X-HTTP-Method-Override'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.header('Access-Control-Allow-Credentials', true); if (req.method === 'OPTIONS') { res.sendStatus(200); } else { next(); } 排行:

ROW_NUMBER