我在 MS SQL 中有两个表:
Category
- Id (int)
CategoryElement
- Id (int)
- CategoryId (int) //References Category.Id
- Time (datetime)
因此,每个类别可以有零个或多个类别元素。时间,在 CategoryElement 中,表示创建类别元素的时间。
我需要一些帮助来编写以下查询:按过去 7 天添加的类别元素数量降序排列类别,并显示类别 ID 和添加的元素数量。
到目前为止,我设法编写了没有“在过去 7 天内添加”部分的查询:
SELECT c.Id, e.ElemCount
FROM dbo.Categories AS c
INNER JOIN
(SELECT CategoryId, COUNT(1) AS ElemCount, MAX(Time) AS LatestElem
FROM dbo.CategoryElements
GROUP BY CategoryId) AS e
ON c.ID = e.CategoryId
ORDER BY e.LatestElem DESC