SQL SERVER 2000 Selecting a record based on an aggregate function
Hi guys here is my working sql query
Select MAX(Hits)'Hits', SUM(Hits)'Total', UserID
From sf_articles
Group By UserID
My problem is, when I want to select other columns as well as the current ones. It gives me a lovely error:
Server: Msg 8120, Level 16, State 1, Line 1
Column 'sf_articles.ArtID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Basically what I want to do is get those columns, and get the info from the records that contain the maximum hits.
For example. I have two records, one with 2 hits, the other with 5. I want to get all the info from the one with 5 hits. There will be an end result of about 7 records at the end since there are 7 users.
PLEASE HELP! I AM TEARING MY HAIR OUT!
Cheers,
Slade
Slade
Practically a Master Poster
633 posts since Mar 2004
Reputation Points: 115
Solved Threads: 7
But the only problem is, I only want to select the records which have the highest hits for each user. If I group by userid, then it singles them down a record from each user. But if I group by userid and artid, then it shows all the records :(. So is there any way to select the record with the highest number of hits for each user?
Slade
Practically a Master Poster
633 posts since Mar 2004
Reputation Points: 115
Solved Threads: 7
Hmm well, this is what I have so far and it works.
CREATE procedure sf_GetMemberInfo
@ArtID int output,
@Title nvarchar(200) output,
@ArticleHits int output,
@UserID nvarchar(20),
@Info nvarchar(1000) output,
@Notes nvarchar(3000) output,
@Favurl nvarchar(60) output,
@FavText nvarchar(200) output,
@PageHits int output
AS
SELECT
@ArtID = ArtID,
@Title = Title,
@ArticleHits = sf_articles.Hits,
@UserID = sf_articles.UserID,
@Info = Info ,
@Notes = Notes,
@Favurl = Favurl,
@FavText = FavText,
@PageHits = sf_Members.Hits + 1
FROM sf_articles, sf_Members
WHERE sf_articles.UserID = @UserID
AND
sf_articles.Hits = (Select MAX(Hits) from sf_articles where UserID = @UserID)
AND
sf_articles.UserID = sf_Members.UserID
UPDATE sf_Members
SET
Hits = Hits + 1
WHERE UserID = @UserID
GO
I guess I"ll have to make an additional query to get the total hits and the total number of records. The above is to work in unison with my asp .net app. I will post a simplified version later.
Slade
Practically a Master Poster
633 posts since Mar 2004
Reputation Points: 115
Solved Threads: 7