>So if psId = 16 has 2 replies and psId = 24 has 2 replies , the
>stored procedure should return the subject associated to psId
>= 16.
Angelo, have a look to this code:
USE tempdb;
GO
CREATE TABLE dbo.forumThreads(
psId int NOT NULL,
psRelTopId int NULL,
psSubject varchar(255) NULL
);
GO
INSERT dbo.forumThreads VALUES(5, 0, 'Where do you play Online?');
INSERT dbo.forumThreads VALUES(11, 0, 'Poker Night at Gina''s during the Month of April');
INSERT dbo.forumThreads VALUES(3, 0, 'Forum rules');
INSERT dbo.forumThreads VALUES(12, 0,'Black Hawk - Isle of Capri');
INSERT dbo.forumThreads VALUES(13, 0, 'UltimateBet.net');
INSERT dbo.forumThreads VALUES(14, 13, 'RE: UltimateBet.net');
INSERT dbo.forumThreads VALUES(15, 0, 'T-SQL Programming');
INSERT dbo.forumThreads VALUES(16, 0, 'Test in Poker Beginners');
INSERT dbo.forumThreads VALUES(17, 16, 'RE: Test in Poker Beginners');
INSERT dbo.forumThreads VALUES(18, 16, 'RE: Test in Poker Beginners');
INSERT dbo.forumThreads VALUES(19, 15, 'RE: T-SQL Programming');
INSERT dbo.forumThreads VALUES(20, 15, 'RE: T-SQL Programming');
GO
/* This query gets the number of answers for every thread */
SELECT psRelTopId, COUNT(*) AS Answers
FROM dbo.forumThreads
WHERE psRelTopId > 0
GROUP BY psRelTopId;
GO
/* Output:
psRelTopId Answers
----------- -----------
13 1
15 2
16 2
(3 row(s) affected)
*/
/* I have to get the first thread with most answers (psRelTopId = 15).
** I can achieve this result ordering the result set in descending order
** by the number of answers and in ascending order by psRelTopId and
** getting only the first row
*/
SELECT TOP 1 psRelTopId, COUNT(*) AS Answers
FROM forumThreads
WHERE psRelTopId > 0
GROUP BY psRelTopId
ORDER BY Answers DESC, psRelTopId;
GO
/* Output:
psRelTopId Answers
----------- -----------
15 2
(1 row(s) affected)
*/
/* OK, and now I need a simple INNER JOIN with the base table
** to get the Subject
*/
SELECT T.psSubject
FROM dbo.forumThreads AS T
JOIN (
SELECT TOP 1 psRelTopId, COUNT(*) AS Answers
FROM forumThreads
WHERE psRelTopId > 0
GROUP BY psRelTopId
ORDER BY Answers DESC, psRelTopId
) AS Q
ON T.psId = Q.psRelTopId;
GO
/* Output:
psSubject
-------------------
T-SQL Programming
(1 row(s) affected)
*/
DROP TABLE dbo.forumThreads;
Ciao!
--
Lorenzo Benaglia
Microsoft MVP - SQL Server
http://blogs.dotnethell.it/lorenzo/
http://italy.mvps.org