tags:

views:

41

answers:

2

What would be the best way to shorten the following SQL Snippet:

SELECT     a.ViewCount, b.DateCreated
FROM         (SELECT COUNT(*) AS ViewCount
              FROM          UserViewHistory uvh1
              WHERE      (UserID = @UserID) AND (ViewedByUserID = @RequestingUserID)) AS a,
             (SELECT     TOP (1) DateCreated
              FROM          UserViewHistory uvh2
              WHERE      (UserID = @UserID) AND (ViewedByUserID = @RequestingUserID)
              ORDER BY DateCreated DESC) b

The idea of the query is the pull the lastviewed date and also the number of views in total - it works as it is, but I was wondering if there was a better way?

Thanks in advance.

A: 

I do not know exactly how DateCreated behaves here, but does this maybe have the desired result?

SELECT Count(*), MAX(DateCreated)
FROM UserViewHistory
WHERE  (UserID = @UserID) AND (ViewedByUserID = @RequestingUserID)

Edit: Removed GROUP BY clause, since it was not neccesary; thanks for the comments!

Jens
ooh, you beat me by 57 seconds :)
PowerUser
From (only) a perfectionist standpoint you don't need the GROUP BY clause, since there will only be one row.
Philip Kelley
@PowerUser: But your answer is better. =) I did not know that MAX() does not need grouping...
Jens
@Philipp: Thanks! Did not know that =)
Jens
+1  A: 

Your style of SQL is a little different from what I'm used to, but this is what I'd recommend.

Select max(datecreated) as [ViewedLast], COUNT(*) AS ViewCount
FROM UserViewHistory uvh1
WHERE (UserID = @UserID) AND (ViewedByUserID = @RequestingUserID)
PowerUser
Thanks for your prompt answer, I actually tried that query in MS SQL Query Designer and as typical must have had typed wrong and not noticed as it simply would not have it - hence I tured something quite trivial into something quite strange and over the top!Thanks again!
Nathan