Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an average from subquery values or another aggregate function in SQL Server

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?

like image 702
simon Avatar asked Sep 08 '09 15:09

simon


People also ask

Which aggregate function will find the average?

AVG() function is an aggregate function that calculates the average value of a numerical dataset that returns from the SELECT statement.

Can we use aggregate function in subquery?

It turned out that subqueries are not allowed in aggregate functions.

Can we use AVG function in WHERE clause?

This query throws an error, because you cannot use AVG() in a WHERE condition. Since AVG() is a group function, you can only use it in a SELECT statement or in a HAVING clause. The query inside a main query is called a subquery.

Is CTE more efficient than subquery?

Advantage of Using CTE Instead of having to declare the same subquery in every place you need to use it, you can use CTE to define a temporary table once, then refer to it whenever you need it. CTE can be more readable: Another advantage of CTE is CTE are more readable than Subqueries.


Video Answer


2 Answers

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 
like image 74
Robin Day Avatar answered Sep 22 '22 00:09

Robin Day


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 
like image 20
eKek0 Avatar answered Sep 22 '22 00:09

eKek0