tags:

views:

33

answers:

2

Hi, I have a table Lets say "TopicComments" which records each comments from every user on a topic. The table has TopicID and UserID as foreign keys and comment date and comment text. So for each user comment, there will be a record with TopicID, UserID, DateTime, and text.

i want to retrieve the topics with most amount of comments within lets say 5 days. Im not the guy with best SQL skills, so im kind of stuck here. Any help would be appreciated. Not sure if my question makes too much sense.

thanks in advance.

A: 

You should use GROUP BY in you sql statement to group all comments by TopicID and than do sum()

Something like that^

SELECT TopicID, sum(UserID) from TopicComments WHERE DateTime > date with 5 days offset GROUP BY TopicID ORDER BY sum(UserID);

kepkin
+1  A: 

Not mentioning the RDBMS, lets say MS SQL

SELECT  TopicID,
        COUNT(1) TotalCount
FROM    TopicComments
WHERE   CommentDate BETWEEN @StartDate AND @EndDate
GROUP BY TopicID
ORDER BY TotalCount DESC

So a full example would look something like

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

Results

TopicID     TotalCount
----------- -----------
1           4
2           2

To select the TOP 1 would then be

SELECT  TOP 1
        TopicID,
        COUNT(1) TotalCount
FROM    @TopicComments
WHERE   CommentDate BETWEEN @StartDate AND @EndDate
GROUP BY TopicID
ORDER BY TotalCount DESC

EDIT

Use somthing like

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
astander
thanks, seems so easy now :) . How do i do it using @startDate=GetDate() and @enddate will be GetDate()-n days?
Joe
Have a look at the edited answer
astander