从类别中选择上周的前5名

时间:2013-03-01 20:36:11

标签: sql sql-server

我在MS SQL中有两个表:

Category
 - Id (int)

CategoryElement
 - Id (int)
 - CategoryId (int) //References Category.Id
 - Time (datetime)

因此,每个类别可以包含零个或多个类别元素。 Time,在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

6 个答案:

答案 0 :(得分:1)

您可以使用DATEDIFFWHERE子句获取上周,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

答案 1 :(得分:0)

看看像:

WHERE (Date(now()) - Date(Time)) < 7

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分:0)

select CategoryId, count(*) as cnt
from CategoryElement
where dateadd(day, -7, getdate())<= Time
group by CategoryID
order by   count(*) desc

答案 5 :(得分:0)

您可以尝试此查询

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

SQLFiddle上的演示

如果你需要TOP 5那么

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