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
Subqueries can contain GROUP BY and ORDER BY clauses. Subqueries cannot contain GROUP BY and ORDER BY clauses.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With