Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause

In the below sql statement i get the following error

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.

How can i get around this?

SELECT
    T.Post,
    COUNT(*) AS ClientCount,
    Client = CASE COUNT(*) WHEN '1' THEN T.Client ELSE '[Clients]' END
FROM
    MyTable T
GROUP BY
    T.Post,
    CASE COUNT(*) WHEN '1' THEN T.Client ELSE '[Clients]' END
like image 984
AzaRoth91 Avatar asked Mar 26 '12 14:03

AzaRoth91


People also ask

Which Cannot be used with subqueries that include group by?

Subqueries can contain GROUP BY and ORDER BY clauses. Subqueries cannot contain GROUP BY and ORDER BY clauses.

Can you use a subquery while also using an aggregate function?

A subquery can also be found in the SELECT clause. These are generally used when you wish to retrieve a calculation using an aggregate function such as the SUM, COUNT, MIN, or MAX function, but you do not want the aggregate function to apply to the main query.

What is a subquery that uses values from the outer query?

In a SQL database query, a correlated subquery (also known as a synchronized subquery) is a subquery (a query nested inside another query) that uses values from the outer query. Because the subquery may be evaluated once for each row processed by the outer query, it can be slow.


2 Answers

Unless you include T.Client in your GROUP BY, you can only include that field within an aggregate function. In your case, grouping by that field changes the logic, so that's out (and is related to your attempt to group by the CASE statement). Instead, wrap T.Client in an aggregate function.

This way your groups are still the same, and when there is only one row, as per your CASE statement's test, you know what result the aggregate funciton is going to give.

SELECT
  T.Post,
  ClientCount = COUNT(*) AS ClientCount,
  Client      = CASE COUNT(*) WHEN 1 THEN MAX(T.Client) ELSE '[Clients]' END
FROM
  MyTable T
GROUP BY
  T.Post
like image 108
MatBailie Avatar answered Oct 17 '22 14:10

MatBailie


You do not need to group by that CASE expression.

SELECT
    T.Post,
    COUNT(*) AS ClientCount,
    CASE COUNT(*) WHEN '1' THEN MIN(T.Client) ELSE '[Clients]' END Client
FROM
    MyTable T
GROUP BY
    T.Post
like image 4
Tomalak Avatar answered Oct 17 '22 15:10

Tomalak