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

后端 未结 2 1059
温柔的废话
温柔的废话 2021-01-12 06:57

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 B

相关标签:
2条回答
  • 2021-01-12 07:41

    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
    
    0 讨论(0)
  • 2021-01-12 07:43

    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
    
    0 讨论(0)
提交回复
热议问题