1

我在 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
4

6 回答 6

1

您可以使用DATEDIFFandWHERE子句仅获取过去一周并将TOP 5结果限制为仅 5 行。

SELECT TOP 5 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
WHERE DATEDIFF(d, e.Time, GetDate()) < 7
ORDER BY e.LatestElem DESC

我上面的回答假设使用 SQL Server。根据您的数据库类型,代码可能会有所变化。例如,对于 MySQL,它将如下所示:

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
WHERE (Date(now()) - Date(e.Time)) < 7
ORDER BY e.LatestElem DESC
LIMIT 5
于 2013-03-01T20:41:12.490 回答
0

You can try this query

SELECT CategoryId, COUNT(*) AS numbOfCat
FROM dbo.CategoryElement
WHERE [Time] BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()
GROUP BY CategoryId
ORDER BY MAX(Time) DESC

Demo on SQLFiddle

If you need TOP 5 then

SELECT TOP 5 CategoryId, COUNT(*) AS numbOfCat
FROM dbo.CategoryElement
WHERE [Time] BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()
GROUP BY CategoryId
ORDER BY MAX(Time) DESC
于 2013-03-01T22:45:47.237 回答
0

看看类似的东西:

WHERE (Date(now()) - Date(Time)) < 7
于 2013-03-01T20:40:59.983 回答
0

不确定您使用的是什么 RDBMS,但在 SQL Server 中您可以执行以下操作:

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
     WHERE DATEDIFF(d, Time, CURRENT_TIMESTAMP) <= 7
     GROUP BY CategoryId) AS e 
ON c.ID = e.CategoryId
ORDER BY e.LatestElem DESC
于 2013-03-01T20:41:23.010 回答
0

您的“最后 7 天”限制将出现在您的内部加入的子查询中。像这样。

SELECT CategoryId, COUNT(1) AS ElemCount, MAX(Time) AS LatestElem
FROM dbo.CategoryElements
WHERE Time > dateadd(dd,-7,getDate()) -- 7 Days prior to today
GROUP BY CategoryId
于 2013-03-01T20:42:58.973 回答
0
select CategoryId, count(*) as cnt
from CategoryElement
where dateadd(day, -7, getdate())<= Time
group by CategoryID
order by   count(*) desc
于 2013-03-01T20:43:38.167 回答