I have a database table that stores document information (DocID, Name, Type, Owner, etc). Then I have another table that stores the times the document has been downloaded (DocID, DownloadTime, etc). I'm trying to set up a page for recording the number of hits that different kinds of documents (policies, forms, publications, etc) get in a specific month and year (I have a dropdown for each that the user selects).
I also want to be able to leave Month or Year empty, so the user can get hits for all months in a year, for example. The query below works ok when the user selects the month and year. However, when month or year is left empty the gridview doesn't show the document types grouped. For example if I want to see hits for January 2010, I get:
Policies : 210 hits
Forms: 98 hits
etc
But when the users chooses all months in 2010, the user gets:
Policies: 210 hits
Policies: 87 hits
Policies: 23 hits
Policies: 87 hits
Forms
etc
So I'm getting all months in different rows but not grouped as one kind. Where is the query wrong?
SELECT COUNT(Counter.DocID) AS Counter,
Doc.DocType,
MONTH(Counter.DownloadDate) AS MonthDownload,
YEAR(Counter.DownloadDate) AS YearDownload
FROM Counter
INNER JOIN Doc ON Counter.DocID = Doc.DocID
GROUP BY Doc.DocType,
MONTH(Counter.DownloadDate),
YEAR(Counter.DownloadDate)
HAVING (MONTH(Counter.DownloadDate) = @Month1 OR @Month1 IS NULL) AND
(YEAR(Counter.DownloadDate) = @Year1 OR @Year1 IS NULL)