views:

419

answers:

3

I writing a query within ms sql server 2005 and having some trouble getting it to run. I need my query to include:

  1. Include all docs from Date Range 2009-07-20 to 2009-08-04
  2. Include a Sum column using the 'Size' field
  3. Include a record count column
  4. Group By Name

    select Name, count(*) AS FileCount, SUM(Size)
    From alldocs Group by DirName HAVING TimeCreated >= '2009-07-20' AND TimeCreated <= '2009-08-04'

A: 

why not

select Name, count(*) AS FileCount, SUM(Size)
From alldocs
WHERE TimeCreated between '2009-07-20' AND '2009-08-04'
Group by DirName

?

streetpc
Will you change field name?
adatapost
+2  A: 

Since you're querying on fields that are not aggregates (SUM, COUNT, AVG), you can use a normal WHERE:

SELECT
  DirName, count(*) AS FileCount, SUM(Size)
FROM
  alldocs 
WHERE
  TimeCreated >= '2009-07-20' 
  AND TimeCreated <= '2009-08-04'
GROUP BY
  DirName

You only need the HAVING if you want to limit something based on an aggreate, e.g.

HAVING Count(*) > 5

Marc

PS: If you want to display MB instead of bytes, use this query:

SELECT
  DirName, count(*) AS FileCount, SUM(Size) / (1024*1024) as 'Size MB'
FROM
  alldocs 
WHERE
  TimeCreated >= '2009-07-20' AND TimeCreated <= '2009-08-04'
GROUP BY
  DirName
marc_s
is there an easy way run a conversion on the size field so that is displays MB verses Bytes?
MG
A: 

You should add the Name column to the Group By list.

SELECT Name, count(*) AS FileCount, SUM(Size)
FROM alldocs
WHERE TimeCreated between '2009-07-20' AND '2009-08-04'
GROUP BY Name