views:

261

answers:

5

I have the SQL statement (SQL Server )


SELECT 
COUNT(ActionName) AS pageCount
FROM tbl_22_Benchmark
WHERE DATEPART(dw,CreationDate)>1 AND DATEPART(dw,CreationDate)<7
GROUP BY 
dateadd(dd,0, datediff(dd,0,CreationDate))

which produces the output

pageCount
27
19
59

Now I would like to get the average of all those figures using SQL. Apparently nested aggregate functions like

(AVG(COUNT(pageCount)))

are not allowed , and using a subquery like


SELECT AVG(pageCount) FROM
(
SELECT 
COUNT(ActionName) AS pageCount
FROM tbl_22_Benchmark
WHERE DATEPART(dw,CreationDate)>1 AND DATEPART(dw,CreationDate)<7
GROUP BY 
dateadd(dd,0, datediff(dd,0,CreationDate))
)

gets me just an error message Incorrect syntax near ')'.

How can I get the average of the pageCount rows?

+2  A: 

in your second attempt you're missing a ) and an alias:

SELECT AVG(pageCount) as AvgPageCount FROM
(
    SELECT 
    COUNT(ActionName) AS pageCount
    FROM tbl_22_Benchmark
    WHERE DATEPART(dw,CreationDate)>1 AND DATEPART(dw,CreationDate)
) t
Mladen Prajdic
+4  A: 

I can't see your whole query as it doesn't seem to have posted correctly.

However, I believe your problem is purely a lack of a name for your derived table / nested subquery.

Give it an alias, such as MyTable in this example

SELECT
 AVG(pageCount)
FROM
(
 SELECT 
  COUNT(ActionName) AS pageCount
 FROM
  tbl_22_Benchmark
) MyTable
Robin Day
Apparently the lesser than character < has to be written as a HTML entity. I had written all the code there, but this prevented the rest of the code showing.Thanks, this seems to solve the problem.
simon
+1  A: 

Add a subquery alias

SELECT AVG(pageCount) 
FROM (SELECT COUNT(ActionName) AS pageCount
      FROM tbl_22_Benchmark
      WHERE DATEPART(dw,CreationDate)>1 
         AND DATEPART(dw,CreationDate) {Missing stuff here } ) AS Z
Charles Bretana
+1  A: 

First of all you shoud add condition on the end of query. For example:

WHERE DATEPART(dw,CreationDate)>1 AND DATEPART(dw,CreationDate) < 10

2nd, you didn't close your bracket at the end. 3rd, you have to name your inner query.

This should work

SELECT AVG(pageCount) FROM
( 
    SELECT 
    COUNT(ActionName) AS pageCount
    FROM tbl_22_Benchmark
    WHERE DATEPART(dw,CreationDate)>1 AND DATEPART(dw,CreationDate) < 10
) myInnerTable
Lukasz Lysik
A: 

Your subquery should have an alias, like in this

SELECT AVG(pageCount) FROM
(
SELECT 
COUNT(ActionName) AS pageCount
FROM tbl_22_Benchmark
WHERE DATEPART(dw,CreationDate)>1 AND DATEPART(dw,CreationDate)<7
GROUP BY 
dateadd(dd,0, datediff(dd,0,CreationDate))
) AS t
eKek0