2013-03-01 95 views
1

在上週選擇前5我在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 
+1

什麼是您使用RDBMS TOP?日期處理功能因此而異。 – 2013-03-01 20:38:42

+0

MSSQL Sever 2008 – user1798724 2013-03-01 21:20:53

回答

0

看是這樣的:

WHERE (Date(now()) - Date(Time)) < 7 
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 
+0

我認爲你在'DATEDIFF'中的參數是倒退的。 – 2013-03-01 20:45:07

+0

他們很好,趕上。 'DATEDIFF'被定義爲'DATEDIFF(datepart,startdate,enddate)'。我已經對我的回答進行了必要的修改。 – Jeremy1026 2013-03-01 20:46:28

+0

謝謝你的回答。但是,它沒有給出正確的結果。最終計數應僅包含上週添加的元素的數量... – user1798724 2013-03-01 21:26:47

0

不知道你正在使用,但在SQL Server中,你可以做什麼RDBMS:

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

你可以試試這個查詢上SQLFiddle

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 

演示如果您需要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