我在这里有一个非常复杂的查询,我试着在这里给你一个关于必要表的概述:
我们每个RPG有X个字符,每个字符有x个帖子。 1用户可以拥有X字符,但1个字符仅取决于1个用户。
我想要的是一个查询,其中我获得了每个RPG的最后一个帖子,其中包含有关写入此用户名的用户名,角色和RPG本身以及每个RPG的RPGPost数量(总数)。
到目前为止我解决了这个问题:
SELECT c.RPGID, c.Name, DateTime, r.Name, u.Username, t.count
FROM dbo.RPGCharacter c inner join
(
SELECT CharacterID,
MAX(DateTime) MaxDate
FROM RPGPost
GROUP BY CharacterID
) MaxDates ON c.RPGCharacterID = MaxDates.CharacterID
INNER JOIN RPGPost p ON MaxDates.CharacterID = p.CharacterID
AND MaxDates.MaxDate = p.DateTime
Inner join RPG r on c.RPGID = r.RPGID
Inner join [User] u on u.UserID = c.OwnerID
inner join (Select RPG.RPGID, Count(*) as Count from RPGPost
inner join RPGCharacter on RPGPost.CharacterID = RPGCharacter.RPGCharacterID
inner join RPG on RPG.RPGID = RPGCharacter.RPGID
where RPGPost.IsDeleted = 0
Group by RPG.RPGID) t on r.RPGID = t.RPGID
Order by DateTime desc
结果:http://abload.de/image.php?img=16iudw.jpg
此查询为我提供了所有我想要但有错误的内容:
1)它给了我每个角色的最后一个帖子,但我需要每个RPG的最后一个帖子
答案 0 :(得分:1)
这有帮助吗?这应该会在CharacterID
表格中为每个RPGPost
提供最后一个帖子,并包含CharacterID
的帖子总数。
WITH RankedPost AS (
SELECT
P.PostID,
P.CharacterID,
P.DateTime
RANK() OVER (
PARTITION BY CharacterID,
ORDER BY DateTime DESC) Rank,
RANK() OVER (
PARTITION BY CharacterID,
ORDER BY DateTime ASC) Count
FROM RPGPost P)
SELECT
P.DateTime
P.CharacterID,
P.Count
FROM RankedPost P
WHERE
RankedPost.Rank = 0;