title: Error: Cannot use an aggregate or a subquery in an expression used for the group by list
body: <p>I'm getting this error: Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.</p>
  
  <p>I searched on internet, but i don't know how to apply the correction in my case. I found different types of query only.</p>
  
  <p>I'm trying to get a Count result in a field (line 5), but when I add the Count query i'm getting this error. </p>
  
  <p>I'm using SQL SERVER 2008 R2.</p>
  
  <p>When I remove the Count from SELECT and GROUP BY the query run correctly.</p>
  
  <pre><code>SELECT TF.COD_FORNECEDOR AS 'Cód. Fornec.',
      TF.NOM_FANTASIA AS 'Fornecedor',
      DM.COD_CONTRATO_RELACIONADO AS 'CONTRATO',
      UA2.NOM_USUARIO AS 'NOM_USUARIO_COMPRADOR',
      (SELECT COUNT(COD_CONTRATO_RELACIONADO) FROM TB_DEMANDA D INNER JOIN TB_PROCESSO P ON D.COD_CONTRATO_RELACIONADO = P.NUM_CONTRATO WHERE D.COD_CONTRATO_RELACIONADO = DM.COD_CONTRATO_RELACIONADO) AS 'NUM_ADITIVO',
      0 AS 'Qtd. Aditivo',
      SUM(DM.VAL_TOTAL_ORCADO) AS 'Valor Inicial',
      SUM(TP.VAL_CONTRATADO) AS 'Valor Final',
      ((SUM(TP.VAL_CONTRATADO) / SUM(DM.VAL_TOTAL_ORCADO)) -1) * 100 AS 'Var. %'
  FROM TB_FORNECEDOR TF 
      LEFT JOIN TB_DEMANDA DM ON DM.COD_FORNECEDOR = TF.COD_FORNECEDOR
      LEFT JOIN TB_PROCESSO TP ON DM.COD_DEMANDA = TP.COD_DEMANDA
      LEFT JOIN TB_PROCESSO_FORNECEDOR PF ON PF.COD_PROCESSO = TP.COD_PROCESSO
      LEFT JOIN USUARIO UA ON UA.NUM_USUARIO = DM.NUM_USUARIO_COMPRADOR
      LEFT JOIN USUARIO UA2 ON UA2.NUM_USUARIO = DM.NUM_USUARIO_COMPRADOR
      LEFT JOIN TB_STATUS_DEMANDA_DATA SD ON SD.COD_DEMANDA = DM.COD_DEMANDA
      LEFT JOIN TB_BASELINE BA ON BA.COD_PROCESSO = TP.COD_PROCESSO
      LEFT JOIN TB_BASELINE_TAREFAS BT ON BT.COD_BASELINE = BA.COD_BASELINE AND BT.COD_PROCESSO = BA.COD_PROCESSO
      LEFT JOIN TB_STATUS_PROCESSO SP ON SP.COD_STATUS = SD.COD_STATUS
      LEFT JOIN TB_MEDIO_STATUS MS ON MS.COD_MEDIO_STATUS = SP.COD_MEDIO_STATUS
      left JOIN #TB_PROCESSO TT ON TT.COD_PROCESSO = TP.COD_PROCESSO
  GROUP BY 
      TF.COD_FORNECEDOR,
      TF.NOM_FANTASIA,
      DM.COD_CONTRATO_RELACIONADO,
      UA2.NOM_USUARIO,
      (SELECT COUNT(COD_CONTRATO_RELACIONADO) FROM TB_DEMANDA D INNER JOIN TB_PROCESSO P ON D.COD_CONTRATO_RELACIONADO = P.NUM_CONTRATO WHERE D.COD_CONTRATO_RELACIONADO = DM.COD_CONTRATO_RELACIONADO)
  ORDER BY TF.NOM_FANTASIA 
  </code></pre>