我有一张表让我们说“TopicComments”,它记录每个用户对主题的每条评论。该表具有TopicID和UserID作为外键和注释日期和注释文本。因此,对于每个用户评论,都会有一个包含TopicID,UserID,DateTime和文本的记录。
我希望在5天内检索具有大量评论的主题。我不是那种具有最佳SQL技能的人,所以我有点卡在这里。任何帮助,将不胜感激。不确定我的问题是否有太多意义。
提前感谢。
答案 0 :(得分:1)
不提RDBMS,比方说MS SQL
SELECT TopicID,
COUNT(1) TotalCount
FROM TopicComments
WHERE CommentDate BETWEEN @StartDate AND @EndDate
GROUP BY TopicID
ORDER BY TotalCount DESC
所以完整示例看起来像
DECLARE @TopicComments TABLE(
TopicID INT,
UserID INT,
CommentDate DATETIME
)
INSERT INTO @TopicComments SELECT 1, 1, '14 Feb 2010'
INSERT INTO @TopicComments SELECT 1, 1, '14 Feb 2010'
INSERT INTO @TopicComments SELECT 1, 2, '14 Feb 2010'
INSERT INTO @TopicComments SELECT 1, 2, '14 Feb 2010'
INSERT INTO @TopicComments SELECT 2, 1, '14 Feb 2010'
INSERT INTO @TopicComments SELECT 2, 1, '14 Feb 2010'
INSERT INTO @TopicComments SELECT 2, 2, '05 Feb 2010'
DECLARE @StartDate DATETIME,
@EndDate DATETIME
SELECT @StartDate = '10 Feb 2010',
@EndDate = '14 Feb 2010'
SELECT TopicID,
COUNT(1) TotalCount
FROM @TopicComments
WHERE CommentDate BETWEEN @StartDate AND @EndDate
GROUP BY TopicID
ORDER BY TotalCount DESC
结果
TopicID TotalCount
----------- -----------
1 4
2 2
选择 TOP 1 将是
SELECT TOP 1
TopicID,
COUNT(1) TotalCount
FROM @TopicComments
WHERE CommentDate BETWEEN @StartDate AND @EndDate
GROUP BY TopicID
ORDER BY TotalCount DESC
修改强>
使用像
这样的东西DECLARE @StartDate DATETIME,
@EndDate DATETIME
SET @EndDate = DATEADD(D, 0, DATEDIFF(D, 0, GETDATE())) --returns only the date part of GETDATE()
SET @StartDate = @EndDate - 5
答案 1 :(得分:0)
您应该在sql语句中使用 GROUP BY 按TopicID对所有注释进行分组,而不是sum()
像那样^
选择TopicID,sum(UserID)来自 TopicComments WHERE DateTime> 日期 5天抵消 GROUP BY TopicID ORDER BY sum(UserID);